Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在尝试学习如何使用原子:)
class foo { static std::atomic<uint32_t> count_; uint32 increase_and_get() { uint32 t = count_++; return t; } }
函数是increase_and_get()线程安全的吗?
increase_and_get()
是的,它是安全的:增量是原子的,并且本地t不能被并发线程更改。您可以进一步简化代码以完全消除临时变量:
t
uint32 increase_and_get() { return count_++; }
是的,这将是线程安全的。当然,假设实现中没有错误std::atomic- 但通常并不难做到正确。
std::atomic
这正是我们std::atomic应该做的。