修改和读取原子变量

Modify and read from an atomic variable

A​​ class 有以下成员,

std::atomic<int> clientId{0};

并在其成员函数中给出以下内容,

int currentId = ++clientId.load();

这里有竞争条件吗?我正在尝试做一些类似于生成 clientId 的事情。多个线程可以执行这部分代码。一个已经递增了 clientId 并且在它尝试加载()并获取副本之前,另一个线程是否可以递增相同的线程并因此以竞争条件结束? 如果是,使用普通 int 并在互斥锁中获取副本的最佳方式是使用互斥锁进行保护吗?

请说明。

std::atomic<int>::load() 没有 return 引用,因此您没有增加 clientId 的当前值,而是增加 return 的临时值 [=13] =].

您需要做的:

int currentId = ++clientId; // no .load()

overloaded operators for std::atomic. The memory order for the pre-increment operator is std:: memory_order_seq_cst1,表示:

A load operation with this memory order performs an acquire operation, a store performs a release operation, and read-modify-write performs both an acquire operation and a release operation, plus a single total order exists in which all threads observe all modifications in the same order (see Sequentially-consistent ordering below)

所以你不会受到这里 data-race 条件的影响。

1 标准说++clientId等价于fetch_add(1) + 1,默认内存顺序为fetch_addstd::memory_order_seq_cst.