Ale*_*x B 1 c++ multithreading atomic
我正在编写一些实现(无符号)整数计数器的代码.
到目前为止,我提出的所有场景都会遇到溢出的竞争条件.是否可以使用这些约束来实现计数器?
您可以通过比较和交换构建所有内容.一般算法是
int DoSomeAtomicCalculation()
{
static int value;
int capture, newValue;
do {
capture = value;
newValue = some_function_based_on(capture);
} while (!compare_and_swap(value, capture, newValue));
return newValue;
}
Run Code Online (Sandbox Code Playgroud)
(我假设它compare_and_swap接受一个变量,一个比较值和一个交换值,并且true如果比较成功(并且发生了交换)则返回.