Issue and get with std :: mutex

This is a question about the C ++ standard. I have access only to the draft standard, so if it is different in the official, I apologize. Also, if I misunderstood how this works, please feel free to correct me.

Suppose I have two streams, one of which is written to a string, and the other is a copy of the contents of this string. I protect their access with std::mutex myMutex; I know that you should use RAII classes for locks, I just used lock and unlock explicitly to make the example more explicit.

 // Global variable std::string message; std::mutex myMutex; // Thread one myMutex.lock(); message = "Hello"; myMutex.unlock(); // Thread two myMutex.lock(); std::string copy = message; myMutex.unlock(); 

I understand that in order for this to work reliably between threads, the thread must perform the Release operation after setting the line, and thead two must execute the Acquire command before reading the line.

Reading the draft standard for C ++ 11 I do not see anything that says std::mutex does this, although it is pretty obvious that it was expecting, or the mutex would be useless for anything.

Can someone point me to the appropriate section to look at? The wording in the standard is often not entirely clear to the casual reader :)

+4
source share
1 answer

Beyond 30.4.1.2p11,

Synchronization: before unlock() operations with the same object must be synchronized with (1.10) [ m.lock() ].

Under 1.10p5,

[...] For example, a call that receives a mutex will perform a receive operation on places containing the mutex. Accordingly, a call that issues the same mutex will perform a release operation in the same places. Unofficially, performing a release operation on A causes previous side effects in other memory locations to become visible to other threads that later perform a consumption or capture operation on A. [...]

+8
source

Source: https://habr.com/ru/post/1445742/


All Articles