Documentation Home >> Headers >> <mutex> Header >> std::try_lock function template

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 the Lockable requirements.

Effects:

Tries to acquires a lock on each of the supplied lockable objects m1, m2, ... by calling try_lock() on each in turn. If a call to try_lock() returns false or throws an exception, and locks already acquired are released by calling unlock() on the corresponding lockable object.

Returns:

-1 if all locks were acquired (each call to try_lock() return true), otherwise the zero-based index of object for which the call to try_lock() returned false.

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_lock then unlock() shall have been called for any of the objects m1, m2, ... for which a lock has been acquired in the function by a call to try_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>

See Also