cpp / latest / thread / unique_lock / try_lock.html /

std::unique_lock<Mutex>::try_lock

bool try_lock();
(since C++11)

Tries to lock (i.e., takes ownership of) the associated mutex without blocking. Effectively calls mutex()->try_lock().

std::system_error is thrown if there is no associated mutex or if the mutex is already locked by this std::unique_lock.

Parameters

(none).

Return value

true if the ownership of the mutex has been acquired successfully, false otherwise.

Exceptions

Example

The following examples try to acquire a mutex that was locked and unlocked.

#include <mutex>
#include <thread>
#include <iostream>
#include <vector>
#include <chrono>
 
int main()
{
    std::mutex counter_mutex;
    std::vector<std::thread> threads;
 
    auto worker_task = [&](int id, int wait_seconds, int acquire_seconds) {
        // wait for a few seconds before acquiring lock.
        std::this_thread::sleep_for(std::chrono::seconds(wait_seconds));
 
        std::unique_lock<std::mutex> lock(counter_mutex, std::defer_lock);
        if (lock.try_lock()) {
            std::cout << id << ", lock acquired.\n";
        } else {
            std::cout << id << ", failed acquiring lock.\n";
            return;
        }
 
        // keep the lock for a while.
        std::this_thread::sleep_for(std::chrono::seconds(acquire_seconds));
 
        std::cout << id << ", releasing lock.\n";
        lock.unlock();
    };
 
    threads.emplace_back(worker_task, 0, 0, 2);
    threads.emplace_back(worker_task, 1, 1, 0);
    threads.emplace_back(worker_task, 2, 3, 0);
 
    for (auto &thread : threads) thread.join();
}

Output:

0, lock acquired.
1, failed acquiring lock.
0, releasing lock.
2, lock acquired.
2, releasing lock.

See also

locks (i.e., takes ownership of) the associated mutex
(public member function)
attempts to lock (i.e., takes ownership of) the associated TimedLockable mutex, returns if the mutex has been unavailable for the specified time duration
(public member function)
tries to lock (i.e., takes ownership of) the associated TimedLockable mutex, returns if the mutex has been unavailable until specified time point has been reached
(public member function)
unlocks (i.e., releases ownership of) the associated mutex
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/thread/unique_lock/try_lock