You've heard wrong. It may well be that "i++"
is thread-safe for a specific compiler and specific processor architecture but it's not mandated in the standards at all. In fact, since multi-threading isn't part of the ISO C or C++ standards (a), you can't consider anything to be thread-safe based on what you think it will compile down to.
这是非常可行的++i
可以编译为任意序列,例如:
load r0,[i] ; load memory into reg 0
incr r0 ; increment reg 0
stor [i],r0 ; store reg 0 back to memory
在我的(假想的)没有内存增量指令的 CPU 上,这不是线程安全的。或者它可能很聪明并将其编译为:
lock ; disable task switching (interrupts)
load r0,[i] ; load memory into reg 0
incr r0 ; increment reg 0
stor [i],r0 ; store reg 0 back to memory
unlock ; enable task switching (interrupts)
where lock
残疾人和unlock
启用中断。但是,即使如此,在具有多个共享内存的 CPU 的体系结构中,这也可能不是线程安全的(lock
只能禁用一个 CPU 的中断)。
语言本身(或它的库,如果它没有内置到语言中)将提供线程安全的构造,您应该使用它们,而不是依赖于您对将生成什么机器代码的理解(或可能误解)。
Things like Java synchronized
and pthread_mutex_lock()
(available to C/C++ under some operating systems) are what you need to look into (a).
(a) This question was asked before the C11 and C++11 standards were completed. Those iterations have now introduced threading support into the language specifications, including atomic data types (though they, and threads in general, are optional, at least in C).