mardi 6 avril 2021

What are the exact inter-thread reordering constraints on mutex.lock() and .unlock() in c++11 and up?

According to https://en.cppreference.com/w/cpp/atomic/memory_order mutex.lock() and mutex.unlock() are acquire and release operations. An acquire operation makes it impossible to reorder later instructions in front of it. And release operations make it impossble to reorder earlier instructions after it. This makes it such that the following code:

[Thread 1]
mutex1.lock();
mutex1.unlock();
mutex2.lock();
mutex2.unlock();
[Thread 2]
mutex2.lock();
mutex2.unlock();
mutex1.lock();
mutex1.unlock();

Can be reordered into the following (possibly deadlocking) code:

[Thread 1]
mutex1.lock();
mutex2.lock();
mutex1.unlock();
mutex2.unlock();
[Thread 2]
mutex2.lock();
mutex1.lock();
mutex2.unlock();
mutex1.unlock();

Is it possible for this reordering to occur. Or is there a rule preventing it?

Aucun commentaire:

Enregistrer un commentaire