I have a multithreaded application, where each thread has a variable of integer type. These variables are incremented during execution of the program. At certain points in the code, a thread compares its counting variable with those of the other threads.
Now since, we know that threads running on multicore might execute out of order, a thread might not read the expected counter values of the other threads. To solve this problem, one way is to use atomic variable, such as std::atomic<> of C++11. However, performing a memory fence at each increment of counters will significantly slow down the program.
Now what I want to do is that when a thread is about to read other thread’s counter, only then a memory fence is created and counters of all the threads are updated in the memory at that point. How can this be done in C++. I am using Linux and g++.
The C++11 standard library includes support for fences in
<atomic>withstd::atomic_thread_fence.Calling this invokes a full fence:
If you want to emit only an acquire or only a release fence, you can use
std:memory_order_acquireandstd::memory_order_releaseinstead.