The std::lock
function template provides a means of locking more than one mutex at the
same time, without risk of deadlock due to inconsistent lock orders.
template<typename LockableType1,typename... LockableType2> void lock(LockableType1& m1,LockableType2& m2...);
- Preconditions:
The types of the supplied lockable objects
LockableType1,LockableType2, ... shall conform to theLockablerequirements.- Effects:
Acquires a lock on each of the supplied lockable objects
m1,m2, ... by an unspecified sequence of calls to thelock(),try_lock()andunlock()members of those types that avoids deadlock.- Postconditions:
The current thread owns a lock on each of the supplied lockable objects.
- Throws:
Any exceptions thrown by the calls to
lock(),try_lock()andunlock().- Note:
If an exception propagates out of the call to
std::lockthenunlock()shall have been called for any of the objectsm1,m2, ... for which a lock has been acquired in the function by a call tolock()ortry_lock().- Note:
On compilers that don't support variadic templates, an overloaded set of function templates is provided that supports passing of up to 5 arguments.
Header
#include <mutex>