non-atomic operations on atomic variables and vice versa

Viewed 96

Given the below code:

static int x;

static void f() {
  for (int i = 0; i < 100; ++i)
    atomic_fetch_add(&x, 3);
}

Further, assume that f is called by two threads concurrently. Does C/C++ memory model guarantee that the result would always be 600 on all hardware platforms?

And what if I changed it to the below? Is the result still guaranteed to be 600 on all hardware platforms?

static atomic_int a_x;

static void f() {
  for (int i = 0; i < 100; ++i)
    a_x += 3;
}

Or the result is not guaranteed and I should never mix atomic operations with non-atomic types and vice versa?

PS: I used an int type here but my question applies to any type T and _Atomic T.

1 Answers

If you want to use atomic operations on non-atomic variables, you can use std::atomic_ref (C++20). You can see an example here.

Your second example should be fine because a_x is atomic with memory_order_seq_cst memory model and += is defined for it as an atomic operation.

Related