在 C++ 中添加两个原子

发布于 2025-01-16 14:26:49 字数 552 浏览 2 评论 0原文

我可以做类似的事情(意味着没有未定义的行为),我不关心顺序:):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏夜暖风 2025-01-23 14:26:49

读取和写入原子变量永远不会导致数据争用,因此如果由于数据争用而在多个线程中不同步地完成,也不会导致未定义的行为,就像普通变量的情况一样。

然而,这并不能阻止竞争条件,尽管没有未定义的行为,但它可能会产生意想不到的结果。例如,这里的 a2 负载可能会读取一个值,该值将被添加到 a1 中,但在将其添加到 a1 之前,会读取 a1 的值>a2 可能会被另一个线程更改。 loadfetch_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 to a1 but before it is added to a1 the value of a2 may be changed by another thread. load and fetch_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文