janekb04
janekb04

Reputation: 4915

Why doesn't `std::lock` lock mutexes using a global ordering?

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 locks, try_locks 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

Answers (2)

David Schwartz
David Schwartz

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

Davis Herring
Davis Herring

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

Related Questions