为什么是std :: atomic< bool>比慢波bool慢得多? [英] Why is std::atomic<bool> much slower than volatile bool?
问题描述
我一直在使用volatile bool多年的线程执行控制,它工作很好
I've been using volatile bool for years for thread execution control and it worked fine
// in my class declaration
volatile bool stop_;
-----------------
// In the thread function
while (!stop_)
{
do_things();
}
现在,由于c ++ 11添加了对原子操作的支持,我决定在我的类声明
std :: atomic< bool>中尝试替代
Now, since c++11 added support for atomic operations, I decided to try that instead
// in my class declaration
std::atomic<bool> stop_;
-----------------
// In the thread function
while (!stop_)
{
do_things();
}
但是它比$ volatile慢几个数量级bool
!
我写的简单测试用例需要大约1秒钟来完成 volatile bool
方法。用 std :: atomic< bool>
但是我一直在等待大约10分钟,放弃了!
Simple test case I've written takes about 1 second to complete with volatile bool
approach. With std::atomic<bool>
however I've been waiting for about 10 minutes and gave up!
我尝试使用 memory_order_relaxed
标志与加载
和存储
效果相同。
I tried to use memory_order_relaxed
flag with load
and store
to the same effect.
我的平台:
Windows 7 64位
MinGW gcc 4.6.x
My platform: Windows 7 64 bit MinGW gcc 4.6.x
我做错了什么?
UPD
volatile不会使可变线程安全。我的问题不是关于挥发性,它是为什么原子是可笑的慢。
Yes, I know that volatile does not make a variable thread safe. My question is not about volatile, it's about why atomic is ridiculously slow.
UPD2
@all,谢谢您的意见
UPD2 @all, thank you for your comments - I will try all the suggested when I get to my machine tonight.
推荐答案
来自Olaf Dietsche的代码
Code from "Olaf Dietsche"
USE ATOMIC
real 0m1.958s
user 0m1.957s
sys 0m0.000s
USE VOLATILE
real 0m1.966s
user 0m1.953s
sys 0m0.010s
如果您使用GCC SMALLER 4.7
http://gcc.gnu.org/gcc-4.7/changes.html
添加了支持指定C ++ 11 / C11内存模型的原子操作。这些新的__atomic例程替换现有的__sync内置例程。
Support for atomic operations specifying the C++11/C11 memory model has been added. These new __atomic routines replace the existing __sync built-in routines.
原子支持也可用于内存块。如果存储器块的大小和对齐方式与支持的整数类型相同,则将使用无锁指令。没有无锁支持的原子操作留作函数调用。
Atomic support is also available for memory blocks. Lock-free instructions will be used if a memory block is the same size and alignment as a supported integer type. Atomic operations which do not have lock-free support are left as function calls. A set of library functions is available on the GCC atomic wiki in the "External Atomics Library" section.
一个库函数集可以在GCC原子维基上在外部原子库是升级到GCC 4.7
So yeah .. only solution is to upgrade to GCC 4.7
这篇关于为什么是std :: atomic< bool>比慢波bool慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!