Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to share variables among threads synchronized with atomic loads and stores?

In a C program compiled under GCC in GNU/Linux, is it safe (In the sense that it won't introduce unexpected behavior) to use non-atomic and non-volatile variables for sharing data between threads provided that the threads that use those variables are synchronized by means of atomic loads and stores?. If not, what should I use instead?.

For instance, does GCC guarantees that the following code will work as expected (thread_2 always returns 1)?. Assume that both functions are invoked from different threads. Would it be any different if it was written using C11 atomic primitives, if I used POSIX threads mutex to synchronize, or if I used POSIX semaphores?. I include the following code as an specific case only.

int data = 0;
int flag = 0;

int thread_1 (void) {
    data = 1;
    __atomic_store_n (&flag, 1, __ATOMIC_RELEASE);
    return -1;
}

int thread_2 (void) {
    while (!__atomic_load_n (&flag, __ATOMIC_ACQUIRE));
    return data;
}

Thanks in advance.

like image 558
Mario Robles Avatar asked Oct 20 '22 18:10

Mario Robles


1 Answers

According to the GCC Wiki this should be safe as the aquire/release memory model guarantees that the store to data in thread 1 will happen-before the atomic store to flag as data is not an atomic variable.

"Any store before an atomic operation must be seen in other threads that synchronize."

Thread 2 will always wait (using busy waiting) until the value of flag differs from zero and then return 1.

like image 197
Felix Glas Avatar answered Oct 22 '22 19:10

Felix Glas