std::unique_lock::lock (3) Linux Manual Page
std::unique_lock<Mutex>::lock – std::unique_lock<Mutex>::lock
Synopsis
void lock();
(since C++ 11)
Locks the associated mutex. Effectively calls mutex()->lock().
Parameters
(none)
Return value
(none)
Exceptions
* Any exceptions thrown by mutex()->lock()
* If there is no associated mutex, std::system_error with an error code of std::errc::operation_not_permitted
* If the mutex is already locked by this unique_lock (in other words, owns_lock is true), std::system_error with an error code of std::errc::resource_deadlock_would_occur
Example
The following example uses lock to re-acquire a mutex that was unlocked.
// Run this code
#include <mutex>
#include <thread>
#include <iostream>
#include <vector>
#include <chrono>
int main()
{
int counter = 0;
std::mutex counter_mutex;
std::vector<std::thread> threads;
auto worker_task = [&](int id) {
std::unique_lock<std::mutex> lock(counter_mutex);
++counter;
std::cout << id << ", initial counter: " << counter << '\n';
lock.unlock();
// don't hold the lock while we simulate an expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
lock.lock();
++counter;
std::cout << id << ", final counter: " << counter << '\n';
};
for (int i = 0; i < 10; ++i)
threads.emplace_back(worker_task, i);
for (auto &thread : threads)
thread.join();
}
Possible output:
See also
try_lock (public member function)
unlock (public member function)
