简体   繁体   English

此功能与原子线程安全吗?

[英]Is this function with atomic thread-safe

I am trying to learn how to use atomic :) 我正在尝试学习如何使用原子:)

class foo {
  static std::atomic<uint32_t> count_;
  uint32 increase_and_get() {
    uint32 t = count_++;
    return t;
  }
}

Is the function increase_and_get() thread-safe? 函数increase_and_get()线程安全的吗?

Yes, it is safe: the increment is atomic, and the local t cannot be altered by concurrent threads. 是的,这很安全:增量是原子的,并且本地t不能被并发线程更改。 You can further simplify your code to eliminate the temporary variable altogether: 您可以进一步简化代码,以完全消除临时变量:

uint32 increase_and_get() {
    return count_++;
}

Yes, it would be threadsafe. 是的,这将是线程安全的。 Assuming of course there are no bugs in the std::atomic implementation - but it's not usually hard to get right. 假设在std::atomic实现中当然没有错误-但是通常不难正确。

This is exactly what std::atomic is meant to do. 这正是std::atomic要做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM