关于这个问题,很少有听到权威的解答。偶这里也只是收集各处资料,以尝试对今后写出高质量的代码做一定的保证。
通常会联想到这个问题应该跟CPU架构相关。优快云上也有人做了实验。根据其结论,在x86上,对1字节byte/2字节word/4字节int类型的读写操作都是原子性的。(类似java中的immutable objects的概念)亦即,1个int不会有中间状态,若它原始值是0,往其写入0x12345678,则另一个线程绝对不会读到0x12000000或是0x00005678的值。
根据偶自己的实验,不但int是原子的,在64位x86上,size_t(8字节)也是原子操作(多核,volatile)。
注意:
1. 通常偶们会以为64位系统中的int是64位的,但实际上不一定,请参见ABI这个概念,简单说就是gcc用-m64参数编译,不加其它选项的话,其int为32位,long也为32位,只有long long, size_t为64位。
2. 根据编译器优化选项不同,以上结论有可能被颠覆:一个64位类型的赋值有可能被编译器编译为两个32位的指令。请在实验时看好自己的编译器(确认反汇编 ^_^)
但是,从收集的资料来看,结果是令人沮丧的。要实现在各种CPU上都通用的原子操作,bool/int都没有得到标准的支持。
写一个字节也不安全?请见下面链接:
主要意思如下:有的架构如Alpha等,根本就没办法实现不读原始值而写1个byte
C++标准也没有规定bool/int类型变量的原子性:
所以C++0x中做出了规定。
有没有绝对支持的平台?在SMP架构的多核CPU环境下,如果读写指令能够编译成1条指令的话,根据其标准,byte和cache line对齐的int/short应该是原子操作:
http://en.wikipedia.org/wiki/Symmetric_multiprocessing
("ram access are serialized")
http://www.blachford.info/computer/articles/bigcrunch1.html
其中的The problem with cache部份
那么,以后是不是bool/int都要加锁了?这个问题偶也没办法回答。大家视情况而定吧。
always be carried out atomically:
• Reading or writing a byte
• Reading or writing a word aligned on a 16-bit boundary
• Reading or writing a doubleword aligned on a 32-bit boundary
The Pentium processor (and newer processors since) guarantees that the following additional memory operations
will always be carried out atomically:
• Reading or writing a quadword aligned on a 64-bit boundary
• 16-bit accesses to uncached memory locations that fit within a 32-bit data bus
The P6 family processors (and newer processors since) guarantee that the following additional memory operation
will always be carried out atomically:
• Unaligned 16-, 32-, and 64-bit accesses to cached memory that fit within a cache line
本文讨论了在C++多线程环境中,int和bool类型的读写操作是否具备原子性。虽然在x86架构上,这些基本类型的操作可能是原子的,但在其他架构如Alpha上并非如此。C++标准并未规定这些类型的原子性,而在C++0x中引入了相关规定。在SMP架构下,对于cache行对齐的int/short和byte,读写可能被认为是原子的。然而,由于编译器优化和不同平台的影响,是否需要加锁仍需根据具体情况进行判断。
1440

被折叠的 条评论
为什么被折叠?



