关于C++多线程程序中简单类型(int/bool)的安全性

来源:互联网 发布:金智慧软件 编辑:程序博客网 时间:2024/05/29 16:17

关于这个问题,很少有听到权威的解答。偶这里也只是收集各处资料,以尝试对今后写出高质量的代码做一定的保证。

通常会联想到这个问题应该跟CPU架构相关。CSDN上也有人做了实验。根据其结论,在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都没有得到标准的支持。

写一个字节也不安全?请见下面链接:

http://stackoverflow.com/questions/15246862/single-byte-write-by-multiple-threads-in-smp-without-using-lock

主要意思如下:有的架构如Alpha等,根本就没办法实现不读原始值而写1个byte

C++标准也没有规定bool/int类型变量的原子性:

http://stackoverflow.com/questions/4936289/is-volatile-a-proper-way-to-make-a-single-byte-atomic-in-c-c

所以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都要加锁了?这个问题偶也没办法回答。大家视情况而定吧。


增注:
本文讨论的是C/C++中int/bool写法的原子性,并非针对特定CPU。若程序目标平台一定是Intel CPU,可参考其架构手册《64-ia-32-architectures》。
摘抄一段如下:
The Intel486 processor (and newer processors since) guarantees that the following basic memory operations will
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
翻译一下最后一段就是说,在P6以上CPU不管有没有进行对齐,只要访问的word/dword/qword所有字节都在cache line内部,就是原子操作。
cache line对齐大小可用以下命令获得:
# cat /proc/cpuinfo
cache_alignment : 64

当然你仍然要记住你写的是C/C++代码,将来它运行的架构并非确定的,所以不能无视C/C++标准。

0 0
原创粉丝点击