这个函数是否具有原子线程安全性

Wha*_*rld 6 c++ atomic c++11

我正在努力学习如何使用原子:)

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)


Mat*_*son 5

是的,这将是线程安全的。当然,假设实现中没有错误std::atomic- 但通常并不难做到正确。

这正是我们std::atomic要做的。