The std::try_lock
function template allows you to try and lock a set of lockable objects
in one go, so either they are all locked or none are locked.
template<typename LockableType1,typename... LockableType2> int try_lock(LockableType1& m1,LockableType2& m2...);
- Preconditions:
The types of the supplied lockable objects
LockableType1,LockableType2, ... shall conform to theLockablerequirements.- Effects:
Tries to acquires a lock on each of the supplied lockable objects
m1,m2, ... by callingtry_lock()on each in turn. If a call totry_lock()returnsfalseor throws an exception, and locks already acquired are released by callingunlock()on the corresponding lockable object.- Returns:
-1 if all locks were acquired (each call to
try_lock()returntrue), otherwise the zero-based index of object for which the call totry_lock()returnedfalse.- Postconditions:
If the function returns -1, the current thread owns a lock on each of the supplied lockable objects. Otherwise, any locks acquired by this call have been released.
- Throws:
Any exceptions thrown by the calls to
try_lock().- Note:
If an exception propagates out of the call to
std::try_lockthenunlock()shall have been called for any of the objectsm1,m2, ... for which a lock has been acquired in the function by a call totry_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>