我听说 i++ 不是线程安全的,++i 线程安全吗?

2023-12-14

我听说 i++ 不是线程安全的语句,因为在汇编中它减少为将原始值存储为临时值,递增它,然后替换它,这可能会被上下文切换中断。

但是,我想知道 ++i 。据我所知,这将减少为一条汇编指令,例如“add r1, r1, 1”,并且由于它只是一条指令,因此它不会被上下文切换中断。

谁能澄清一下吗?我假设正在使用 x86 平台。


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).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我听说 i++ 不是线程安全的,++i 线程安全吗? 的相关文章

随机推荐