问题描述
是原子类型的C/C ++基本类型,例如int
,double
等.线程安全的?
他们是否摆脱了数据竞争;也就是说,如果一个线程向这种类型的对象写入而另一线程从该对象读取,则行为是否定义明确?
如果不是,这取决于编译器还是其他工具?
否,基本数据类型(例如int
,double
)不是原子的,请参见.
您可以使用std::atomic<int>
或std::atomic<double>
.
注意: std::atomic
是C ++ 11引入的,我的理解是,在C ++ 11之前,C ++标准根本不认识多线程的存在. >
@Josh指出, std::atomic_flag
是原子布尔类型.与std::atomic
专门技术不同,它保证无锁.
引用的文档来自: http://open-std.org /JTC1/SC22/WG21/docs/papers/2015/n4567.pdf .我很确定该标准不是免费的,因此这不是最终/官方版本.
1.10多线程执行和数据争用
29.5原子类型
29.7标志类型和操作
Are C/C++ fundamental types, like int
, double
, etc., atomic, e.g. threadsafe?
Are they free from data races; that is, if one thread writes to an object of such a type while another thread reads from it, is the behavior well-defined?
If not, does it depend on the compiler or something else?
No, fundamental data types (e.g., int
, double
) are not atomic, see std::atomic
.
Instead you can use std::atomic<int>
or std::atomic<double>
.
Note: std::atomic
was introduced with C++11 and my understanding is that prior to C++11, the C++ standard didn't recognize the existence of multithreading at all.
As pointed out by @Josh, std::atomic_flag
is an atomic boolean type. It is guaranteed to be lock-free, unlike the std::atomic
specializations.
The quoted documentation is from: http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4567.pdf. I'm pretty sure the standard is not free and therefore this isn't the final/official version.
1.10 Multi-threaded executions and data races
29.5 Atomic types
29.7 Flag type and operations
这篇关于C/C ++基本类型是原子类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!