Search code examples
c++multithreadingatomicstdatomic

Usage of an atomic variable within threads


Consider a program with three threads A,B,C.

They have a shared global object G.

I want to use an atomic variable(i) inside G which is written by Thread B and Read by A.

My approach was:

declare i in G as:

std::atomic<int> i;

write it from thread B using a pointer to G as:

G* pG; //this is available inside A and B 

pG->i = 23;

And read it from thread A using the same way.

int k = pG->i;

Is my approach correct if these threads try to access this variable simultaneously.?


Solution

  • Like JV says, it depends what your definition of "correct" is. See http://preshing.com/20120612/an-introduction-to-lock-free-programming/. If it doesn't need to synchronize with anything, you should use std::memory_order_relaxed stores instead of the default sequential consistency stores, so it compiles to more efficient asm (no memory barrier instructions).

    But yes, accessing an atomic struct member through a pointer is fine, as long as the pointer itself is initialized before the threads start.

    If the struct is a global, then don't use a pointer to it, just access the global directly. Having a separate variable that always points to the same global is an extra level of indirection for no benefit.

    If you want to change the pointer, it also needs to be std::atomic<struct foo *> pG, and changing it gets complicated as far as deciding when it's safe to free the old data after changing it.