我正在努力学习如何使用原子:)
class foo {
static std::atomic<uint32_t> count_;
uint32 increase_and_get() {
uint32 t = count_++;
return t;
}
}
Run Code Online (Sandbox Code Playgroud)
功能是increase_and_get()线程安全的吗?
das*_*ght 11
是的,它是安全的:增量是原子的,并且本地t不能被并发线程改变.您可以进一步简化代码以完全消除临时变量:
uint32 increase_and_get() {
return count_++;
}
Run Code Online (Sandbox Code Playgroud)