对原子变量的非原子操作,反之亦然
non-atomic operations on atomic variables and vice versa
给定以下代码:
static int x;
static void f() {
for (int i = 0; i < 100; ++i)
atomic_fetch_add(&x, 3);
}
进一步假设f
被两个线程同时调用。 C/C++ 内存模型是否保证在所有硬件平台上结果总是 600
?
如果我把它改成下面的呢?结果是否仍然保证在所有硬件平台上都是600
?
static atomic_int a_x;
static void f() {
for (int i = 0; i < 100; ++i)
a_x += 3;
}
或者不能保证结果,我不应该将原子操作与非原子类型混合使用,反之亦然?
PS:我在这里使用了 int 类型,但我的问题适用于任何类型 T
和 _Atomic T
.
如果想对非原子变量使用原子操作,可以使用std::atomic_ref (C++20). You can see an example here。
你的第二个例子应该没问题,因为 a_x
是原子的 memory_order_seq_cst
内存模型,+=
是 defined 作为原子操作。
给定以下代码:
static int x;
static void f() {
for (int i = 0; i < 100; ++i)
atomic_fetch_add(&x, 3);
}
进一步假设f
被两个线程同时调用。 C/C++ 内存模型是否保证在所有硬件平台上结果总是 600
?
如果我把它改成下面的呢?结果是否仍然保证在所有硬件平台上都是600
?
static atomic_int a_x;
static void f() {
for (int i = 0; i < 100; ++i)
a_x += 3;
}
或者不能保证结果,我不应该将原子操作与非原子类型混合使用,反之亦然?
PS:我在这里使用了 int 类型,但我的问题适用于任何类型 T
和 _Atomic T
.
如果想对非原子变量使用原子操作,可以使用std::atomic_ref (C++20). You can see an example here。
你的第二个例子应该没问题,因为 a_x
是原子的 memory_order_seq_cst
内存模型,+=
是 defined 作为原子操作。