Is it possible to have a
scoped_lock
with a timeout to wait N seconds/millis to acquire the lock?
std::scoped_lock
does not have a built-in timeout mechanism in C++. std::scoped_lock
is a simple RAII wrapper that blocks indefinitely until it acquires the lock(s).
The class
scoped_lock
is a mutex wrapper that provides a convenient RAII-style mechanism for owning zero or more mutexes for the duration of a scoped block.When a
scoped_lock
object is created, it attempts to take ownership of the mutexes it is given. When control leaves the scope in which thescoped_lock
object was created, thescoped_lock
is destructed and the mutexes are released. If several mutexes are given, deadlock avoidance algorithm is used as if by std::lock.The
scoped_lock
class is non-copyable.
And:
Tries to lock (i.e., takes ownership of) the associated mutex. Blocks until specified timeout_duration has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns true, otherwise returns false. Effectively calls mutex()->try_lock_for(timeout_duration).
This function may block for longer than timeout_duration due to scheduling or resource contention delays.
The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments.
std::system_error is thrown if there is no associated mutex or if the mutex is already locked by this std::unique_lock.