在 C++ 中添加两个原子
我可以做类似的事情(意味着没有未定义的行为),我不关心顺序:):
typedef std::atomic<double> a_t;
static a_t a1(1);
static a_t a2(2);
static a_t a3(3);
void f1()
{
a1.fetch_add(a2.load(std::memory_order::relaxed), std::memory_order::relaxed);
};
void f2()
{
a1.fetch_add(a3.load(std::memory_order::relaxed), std::memory_order::relaxed);
};
th1 = std::thread(f1);
th2 = std::thread(f2);
th1.join();
th2.join();
谢谢!
PS:这个例子只是为了提问!
在这条评论“我有一种感觉,你的例子......”之后,我添加了以下内容 PS:假设许多线程在上例中的原子之上写入和读取所有这些原子。
can I do something like (meaning no undefined behaviour), I don't care about the order :) :
typedef std::atomic<double> a_t;
static a_t a1(1);
static a_t a2(2);
static a_t a3(3);
void f1()
{
a1.fetch_add(a2.load(std::memory_order::relaxed), std::memory_order::relaxed);
};
void f2()
{
a1.fetch_add(a3.load(std::memory_order::relaxed), std::memory_order::relaxed);
};
th1 = std::thread(f1);
th2 = std::thread(f2);
th1.join();
th2.join();
Thank you!
Ps: This example is just for the sake of the question!
After this comment "I have a feeling that your example..." I added the below
Ps: Suppose many threads write and read from all these atomics on top on the one in the example above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
读取和写入原子变量永远不会导致数据争用,因此如果由于数据争用而在多个线程中不同步地完成,也不会导致未定义的行为,就像普通变量的情况一样。
然而,这并不能阻止竞争条件,尽管没有未定义的行为,但它可能会产生意想不到的结果。例如,这里的
a2
负载可能会读取一个值,该值将被添加到a1
中,但在将其添加到a1
之前,会读取a1
的值>a2 可能会被另一个线程更改。load
和fetch_add
单独是原子的,但整个表达式不是。通过宽松的操作,线程也不必同意多个原子变量的修改顺序。只有任何给定的单个原子的修改顺序是一致的。
Reading and writing to atomic variables never causes data races and so doesn't cause undefined behavior if done unsynchronized in multiple threads for reason of a data race, as would be the case for normal variables.
However, this doesn't prevent race conditions, which can have unexpected results, although no undefined behavior. For example here a load of
a2
may read one value which will be added toa1
but before it is added toa1
the value ofa2
may be changed by another thread.load
andfetch_add
are individually atomic, but the whole expression is not.With relaxed operations threads also don't have to agree with the order in which multiple atomic variables are modified. Only the modification order of any given individual atomic is consistent.