unique_lock
template <class Mutex> class unique_lock;
A unique lock is an object that manages a mutex object with unique ownership in both states: locked and unlocked.
On construction (or by move-assigning to it), the object acquires a mutex object, for whose locking and unlocking operations becomes responsible.
The object supports both states: locked and unlocked.
This class guarantees an unlocked status on destruction (even if not called explicitly). Therefore it is especially useful as an object with automatic duration, as it guarantees the mutex object is properly unlocked in case an exception is thrown.
Note though, that the unique_lock object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the unique_lock that manages it.
http://www.cplusplus.com/reference/mutex/unique_lock/
<mutex> 頭文件介紹
Mutex 系列類(四種)
- std::mutex,最基本的 Mutex 類。
- std::recursive_mutex,遞歸 Mutex 類。
- std::time_mutex,定時 Mutex 類。
- std::recursive_timed_mutex,定時遞歸 Mutex 類。
Lock 類(兩種)
- std::lock_guard,與 Mutex RAII 相關,方便線程對互斥量上鎖。
- std::unique_lock,與 Mutex RAII 相關,方便線程對互斥量上鎖,但提供了更好的上鎖和解鎖控制。
// unique_lock example #include <iostream> // std::cout #include <thread> // std::thread #include <mutex> // std::mutex, std::unique_lock std::mutex mtx; // mutex for critical section void print_block (int n, char c) { // critical section (exclusive access to std::cout signaled by lifetime of lck): std::unique_lock<std::mutex> lck (mtx); for (int i=0; i<n; ++i) { std::cout << c; } std::cout << '\n'; } int main () { std::thread th1 (print_block,50,'*'); std::thread th2 (print_block,50,'$'); th1.join(); th2.join(); return 0; } Edit & Run
一篇文章:
boost庫中thread多線程詳解3——細說lock_guard
boost::lock_guard可以說是一種比boost::unique_lock輕量級的lock, 簡單一些場景可以用它就行了。
看看它的源代碼也很簡單:
template<typename Mutex> class lock_guard { private: Mutex& m; explicit lock_guard(lock_guard&); lock_guard& operator=(lock_guard&); public: explicit lock_guard(Mutex& m_): m(m_) { m.lock(); } lock_guard(Mutex& m_,adopt_lock_t): m(m_) {} ~lock_guard() { m.unlock(); } };
可以看到只有兩個public方法,即構造和析構函數,也就是說,使用boost::lock_guard去guard一個mutex,必然是在boost::lock_guard的對象離開其作用域時unlock它所guard的mutex,不提供提前unlock的功能。
而boost::unique_lock則提供這個功能,除了像boost::lock_guard一樣在離開作用域時unlock它guard的mutex外,boost::unique還提供unlock函數,使用者可以手動執行unlock。此外,unique_lock還可以設置超時。