|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Locking | ||||
unique_lock::lock | ||||
| Modifiers | ||||
| Observers | ||||
| Non-member functions | ||||
void lock(); | (since C++11) | |
Locks (i.e., takes ownership of) the associated mutex. Effectively callsmutex()->lock().
Contents |
(none)
(none)
unique_lock (in other words,owns_lock() istrue),std::system_error with an error code ofstd::errc::resource_deadlock_would_occur.The following example useslock to re-acquire a mutex that was unlocked.
#include <chrono>#include <iostream>#include <mutex>#include <thread>#include <vector> 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 operationstd::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:
0, initial counter: 11, initial counter: 22, initial counter: 33, initial counter: 44, initial counter: 55, initial counter: 66, initial counter: 77, initial counter: 88, initial counter: 99, initial counter: 106, final counter: 113, final counter: 124, final counter: 132, final counter: 145, final counter: 150, final counter: 161, final counter: 177, final counter: 189, final counter: 198, final counter: 20
| tries to lock (i.e., takes ownership of) the associated mutex without blocking (public member function)[edit] | |
| unlocks (i.e., releases ownership of) the associated mutex (public member function)[edit] |