Reputation: 4915
std::lock
and std::scoped_lock
can be used to lock a series of mutexes while avoiding a deadlock. Apparently, they use some algorithm composed of lock
s, try_lock
s and unlocks
to achieve this.
As it should be simpler, couldn't std::lock
and std::scoped_lock
lock the mutexes using some kind of global ordering (such as their address taken with &
), as a deadlock does not occur when mutexes are always locked in the same order?
Upvotes: 1
Views: 121
Reputation: 182753
That can deadlock with other algorithms. Suppose one lock protects a collection of objects and another lock protects an individual object in that collection. Code that doesn't call std::lock
will lock the collection first, then find the object, and then want to acquire the lock that protects that particular object.
If your algorithm was used, then what happens if code in the object uses std::lock
to acquire both locks and your algorithm says to acquire the lock that protects the object before the lock that protects the collection? It would deadlock.
Upvotes: 1
Reputation: 39788
The algorithm works for any lockable object—some of those might be wrappers for other locks (like std::unique_lock
), so checking addresses would be insufficient. Nothing stops the library from recognizing that all types involved are “primitive” locks from the standard library and applying your suggestion.
Upvotes: 1