0

Let say I've got some std::mutex Mutex and a code like this:

...

Mutex.lock()
expr;
Mutex.unlock()
...

cppreference on unlock only says that an unlock() may synchronize with a lock() (which may give inter-threads synchronization relationships).
But I can find anything about compiler reordering with respect to the snippet above. Does lock() behave like an acquire operation and prevent expr to be evaluated before it? Does unlock() behave like a release operation and prevent expr to be evaluated after it? this SO answer seems to say so but seems to be specific to some implementation of mutexes.
Another SO answer tries to be more general but, IMHO, it's more a rather free interpretation of some parts of the standard than a "legal" argument.
Is there something more explicit in cppreference or, better, within the standard?

Actually, it's more than a theoretical question. In a real use case I've got a snippet like this:

...
Mutex.lock()
expr1;
Mutex.unlock()
expr2;
...

And I want to be sure that expr1 cannot be evaluated after expr2.

Oersted
  • 769
  • 16
  • a mutex would be pretty useless if there was no guarantee that the code it was protecting would stay inside the protected block – Alan Birtles Jul 18 '23 at 14:23
  • @AlanBirtles Indeed. Yet it cannot be deduced by the simple fact that ```lock()``` will block on already locked mutex and from the synchronize with relationship (which is an interthread property). But it makes my question more academic than practical... – Oersted Jul 18 '23 at 14:33
  • @AlanBirtles maybe that, as the ```lock()``` may be synchronize with a previous ```unlock()``` the compiler must leave expressions after lock(), after it, otherwise the relationship may not hold? Eventually it would be a consequence of the inter-thread property... – Oersted Jul 18 '23 at 14:51

0 Answers0