Memory fence in gcc 4.8 (and newer)
by NevemTeve from LinuxQuestions.org on (#4XXQ1)
Hi, I'm trying to find some portable way to create a memory fence (aka memory barrier) in a multithreaded program that should run on Linux and AIX, compiled with gcc-4.8.x or newer (though it wouldn't hurt if the solution weren't gcc-specific).
Gcc-4.8.x doesn't support C11 stdatomic.h but it has __sync_synchronize
In newer gcc versions there is atomic_thread_fence from stdatomic.h
Also some pthread-functions imply memory fence as a side-effect but I didn't find a standalone 'pthread_msync' (or similar).
Also some other functions (e.g. semop) imply memory fence.
Right now I think it will be some #ifdef-hacking depending on gcc-version, but I would like to hear some better suggestions.
Note: part of the problem is that instead of semaphores/mutexes I use pipes for thread-synchronization/communication as it feels more flexible: for example you cannot wait for two or more semaphores/mutexes in the same time, but you can wait for two or more pipes to become readable with select(2).


Gcc-4.8.x doesn't support C11 stdatomic.h but it has __sync_synchronize
In newer gcc versions there is atomic_thread_fence from stdatomic.h
Also some pthread-functions imply memory fence as a side-effect but I didn't find a standalone 'pthread_msync' (or similar).
Also some other functions (e.g. semop) imply memory fence.
Right now I think it will be some #ifdef-hacking depending on gcc-version, but I would like to hear some better suggestions.
Note: part of the problem is that instead of semaphores/mutexes I use pipes for thread-synchronization/communication as it feels more flexible: for example you cannot wait for two or more semaphores/mutexes in the same time, but you can wait for two or more pipes to become readable with select(2).