增量器/减量器(var ++,var--)等线程安全吗? [英] Are incrementers / decrementers (var++, var--) etc thread safe?
问题描述
受此问题启发:在复杂度分析"中为什么++被认为是2个运算?
输入以下伪代码:
class test
{
int _counter;
void Increment()
{
_counter++;
}
}
在x86 architechure上将其视为线程安全的吗?另外,Inc/Dec汇编说明中的线程安全吗?
Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?
推荐答案
否,递增不是线程安全的. INC
和DEC
指令都没有.它们都需要加载和存储,并且在另一个CPU上运行的线程可以自己进行加载或存储在这些操作之间交错的同一内存位置.
No, incrementing is not thread-safe. Neither are the INC
and DEC
instructions. They all require a load and a store, and a thread running on another CPU could do its own load or store on the same memory location interleaved between those operations.
某些语言内置了对线程同步的支持,但这通常是您所需要的,而不是在每个变量上自动获得的.那些没有内置支持的用户通常可以访问提供类似功能的库.
Some languages have built-in support for thread synchronization, but it's usually something you have to ask for, not something you get automatically on every variable. Those that don't have built-in support usually have access to a library that provides similar functionality.
这篇关于增量器/减量器(var ++,var--)等线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!