Can I read an atomic variable without atom_load?

I have a situation with one writer, with several readers. There is a counter on which one thread writes, and any thread can read this counter. Since you don’t have to worry about fighting with other streams to access data for one recording stream, is the following code safe?

#include <stdatomic.h>
#include <stdint.h>

_Atomic uint32_t counter;

// Only 1 thread calls this function. No other thread is allowed to.
uint32_t increment_counter() {
    atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
    return counter;  // This is the line in question.
}

// Any thread may call this function.
uint32_t load_counter() {
    return atomic_load_explicit(&counter, memory_order_relaxed);
}

The writer thread simply reads counterdirectly without calling any function atomic_load*. This should be safe (since you need to read a value to read multiple lines), but I don’t know if the variable declaration forbids _Atomicusing this variable directly or if you should always read it using one function atomic_load*.

+4
2

, , _Atomic, , . atomic_load.

, , atomic_fetch_add , .

uint32_t ret = atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
return ret+1;

, , .

+1

, :

uint32_t increment_counter() {
    return 1 + atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
}
0

Source: https://habr.com/ru/post/1668635/


All Articles