【问题标题】:Is this function with atomic thread-safe这个函数是原子线程安全的吗
【发布时间】:2013-02-27 02:18:37
【问题描述】:

我正在尝试学习如何使用 atomic :)

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

函数increase_and_get()是线程安全的吗?

【问题讨论】:

  • 它的实现方式我称之为get_and_increase而不是increase_and_get

标签: c++ c++11 atomic


【解决方案1】:

是的,它是安全的:增量是原子的,本地的t 不能被并发线程改变。您可以进一步简化代码以完全消除临时变量:

uint32 increase_and_get() {
    return count_++;
}

【讨论】:

  • 如果没有原子,则不能保证内存位置的增量是原子的,不。即使在 x86 上,也有可能两个处理器尝试同时递增,如果没有原子,它可能会导致来自两个不同调用的相同值。 (回复已删除的评论!)
  • @MatsPetersson 这就是std::atomic 的重点,不是吗?
  • 我刚刚编辑了我的评论 - 请注意,这是对显然已被删除的评论的回复。
【解决方案2】:

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

这正是std::atomic 的本意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多