多年来,我一直在使用 volatile bool 进行线程执行控制,效果很好
// in my class declaration
volatile bool stop_;
-----------------
// In the thread function
while (!stop_)
{
do_things();
}
现在,由于 C++11 增加了对原子操作的支持,我决定尝试一下
// in my class declaration
std::atomic<bool> stop_;
-----------------
// In the thread function
while (!stop_)
{
do_things();
}
但它比 volatile bool
慢了几个数量级!
我编写的简单测试用例使用 volatile bool
方法大约需要 1 秒才能完成。使用 std::atomic<bool>
但是我已经等了大约 10 分钟然后放弃了!
我尝试使用 memory_order_relaxed
标志与 load
和 store
达到相同的效果。
我的平台:
- Windows 7 64 位
- MinGW gcc 4.6.x
我做错了什么?
注意:我知道 volatile 不会使变量成为线程安全的。我的问题不是关于 volatile,而是关于为什么 atomic 慢得离谱。
原文由 user1773602 发布,翻译遵循 CC BY-SA 4.0 许可协议
来自“Olaf Dietsche”的代码
如果您使用的是 GCC SMALLER 4.7
http://gcc.gnu.org/gcc-4.7/changes.html
所以是的..唯一的解决方案是升级到 GCC 4.7