Re: What in C++11 prohibits mutex operations from being reordered?
On Thursday, 4 April 2013 05:58:45 UTC+3, Michael Podolsky wrote:
On Apr 3, 12:59 pm, =D6=F6 Tiib <oot...@hot.ee> wrote:
Let me try to write
example that achieves some synchronization ...
// bool that tells that thread 1 is done with data. It is
// atomic just because standard does not guarantee that accesses to
// bool are atomic.
std::atomic<bool> ready(false);
// the ordinary data
int data=0;
void thread_1()
{
// these lines can't be reordered in any way
data=42;
std::atomic_thread_fence(std::memory_order_release);
ready.store(true,std::memory_order_relaxed);
}
void thread_2()
{
if(ready.load(std::memory_order_relaxed))
{
// these lines can't be reordered
std::atomic_thread_fence(std::memory_order_acquire)=
;
std::cout<<"data="<<data<<std::endl;
}
}
The effect is that thread 2 does not touch data if thread 1
is not ready with it. So access to non-atomic "data" is safe, synchroni=
zed
and no data race is possible.
Yep, this is a very basic stuff as for memory ordering in C++. Sorry,
do not see a relation to the discussed problem.
So you find above very basic. Relaxed ready.store can't become
visible in thread 2 before data=42. Yet you do not for some reason see an=
y relation with the mutex2 locking that you somehow feel may happen and
become visible in thread 2 before data=42 like that:
void thread_1()
{
// these lines can't be reordered in any way
data=42;
std::atomic_thread_fence(std::memory_order_release);
mutex2.lock();
// ...
// ...
}
I am in difficulties to understand what is the reason why you see
the relaxed atomic bool access can be ordered better than mutex lock?