Question Details

No question body available.

Tags

c++

Answers (3)

Accepted Answer Available
Accepted Answer
September 18, 2025 Score: 5 Rep: 225,512 Quality: Expert Completeness: 80%

The language of your question implies a single mutex that you are trying to perform a timed lock on with an RAII device. If that is the case, std::uniquelock paired with a std::timedmutex is the tool you are looking for.

#include 
#include 
#include 

std::timedmutex mut;

int main() { using namespace std::literals; std::unique
lock lk{mut, 157ms}; // or 3s, 6ns, whatever if (lk.owns_lock()) std::cout
September 17, 2025 Score: 6 Rep: 23,310 Quality: Medium Completeness: 70%

std::scopedlock is the utility that will call unlock() in destructor on all owned mutexes. So wherever in the example you have unlock() call, you can mentally replace it by "std::scopedlock-end-of-life".

Do note that you need std::adoptlock if you want to use timeout versions of trylock(), as std::scopedlock doesn't know how to use them:

std::timed
mutex m; if (m.trylockfor(1s)) { std::scopedlock lock {std::adoptlock, m}; // you have mutex here, it will be released automatically at the end of scope } else { // you didn't acquire mutex }
September 17, 2025 Score: 0 Quality: Low Completeness: 80%

Is it possible to have a scopedlock with a timeout to wait N seconds/millis to acquire the lock?

std::scopedlock does not have a built-in timeout mechanism in C++. std::scopedlock is a simple RAII wrapper that blocks indefinitely until it acquires the lock(s).

The class scopedlock 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 scopedlock object is created, it attempts to take ownership of the mutexes it is given. When control leaves the scope in which the scopedlock object was created, the scopedlock is destructed and the mutexes are released. If several mutexes are given, deadlock avoidance algorithm is used as if by std::lock.

The scopedlock class is non-copyable.

And:

Tries to lock (i.e., takes ownership of) the associated mutex. Blocks until specified timeoutduration has elapsed or the lock is acquired, whichever comes first. On successful lock acquisition returns true, otherwise returns false. Effectively calls mutex()->trylockfor(timeoutduration).

This function may block for longer than timeoutduration 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::systemerror is thrown if there is no associated mutex or if the mutex is already locked by this std::unique_lock.