C++11中std::unique_lock的使用
std::unique_lock為鎖管理模板類,是對通用mutex的封裝。std::unique_lock對象以獨占所有權的方式(unique owership)管理mutex對象的上鎖和解鎖操作,即在unique_lock對象的聲明周期內,它所管理的鎖對象會一直保持上鎖狀態;而unique_lock的生命周期結束之后,它所管理的鎖對象會被解鎖。unique_lock具有lock_guard的所有功能,而且更為靈活。雖然二者的對象都不能復制,但是unique_lock可以移動(movable),因此用unique_lock管理互斥對象,可以作為函數的返回值,也可以放到STL的容器中。
關于std::mutex的基礎介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/73521630??
std::unique_lock還支持同時鎖定多個mutex,這避免了多道加鎖時的資源”死鎖”問題。在使用std::condition_variable時需要使用std::unique_lock而不應該使用std::lock_guard。
std::unique_lock類成員函數介紹:
(1). unique_lock構造函數:禁止拷貝構造,允許移動構造;
(2). operator =:賦值操作符,允許移動賦值,禁止拷貝賦值;
(3). operator bool:返回當前std::unique_lock對象是否獲得了鎖;
(4). lock函數:調用所管理的mutex對象的lock函數;
(5). try_lock函數:調用所管理的mutex對象的try_lock函數;
(6).try_lock_for函數:調用所管理的mutex對象的try_lock_for函數;
(7).try_lock_until函數:調用所管理的mutex對象的try_lock_until函數;
(8). unlock函數:調用所管理的mutex對象的unlock函數;
(9). release函數:返回所管理的mutex對象的指針,并釋放所有權,但不改變mutex對象的狀態;
(10). owns_lock函數:返回當前std::unique_lock對象是否獲得了鎖;
(11). mutex函數:返回當前std::unique_lock對象所管理的mutex對象的指針;
(12). swap函數:交換兩個unique_lock對象。
The difference is that you can lock and unlock a std::unique_lock. std::lock_guard will be locked only once on construction and unlocked on destruction.
std::unique_lock has other features that allow it to e.g.: be constructed without locking the mutex immediately but to build the RAII wrapper. However, std::unique_lock might have a tad more overhead(較多開銷).
std::lock_guard also provides a convenient RAII wrapper, but cannot lock multiple mutexes safely. It can be used when you need a wrapper for a limited scope, e.g.: a member function.
One of the differences between std::lock_guard and std::unique_lock is that the programmer is able to unlock std::unique_lock, but she/he is not able to unlock std::lock_guard.
下面是從其他文章中copy的測試代碼,詳細內容介紹可以參考對應的reference:
#include "unique_lock.hpp"
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <chrono>namespace unique_lock_ {//
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/unique_lock/
namespace {
std::mutex foo, bar;void task_a()
{std::lock(foo, bar); // simultaneous lock (prevents deadlock)std::unique_lock<std::mutex> lck1(foo, std::adopt_lock);std::unique_lock<std::mutex> lck2(bar, std::adopt_lock);std::cout << "task a\n";// (unlocked automatically on destruction of lck1 and lck2)
}void task_b()
{// unique_lock::unique_lock: Constructs a unique_lock// foo.lock(); bar.lock(); // replaced by:std::unique_lock<std::mutex> lck1, lck2;lck1 = std::unique_lock<std::mutex>(bar, std::defer_lock);lck2 = std::unique_lock<std::mutex>(foo, std::defer_lock);std::lock(lck1, lck2); // simultaneous lock (prevents deadlock)std::cout << "task b\n";// (unlocked automatically on destruction of lck1 and lck2)
}
}int test_unique_lock_1()
{std::thread th1(task_a);std::thread th2(task_b);th1.join();th2.join();return 0;
}/
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/lock/
namespace {
std::mutex mtx; // mutex for critical sectionvoid print_thread_id(int id) {std::unique_lock<std::mutex> lck(mtx, std::defer_lock);// critical section (exclusive access to std::cout signaled by locking lck):// unique_lock::lock: Calls member lock of the managed mutex object.lck.lock();std::cout << "thread #" << id << '\n';// unique_lock::unlock: Calls member unlock of the managed mutex object, and sets the owning state to falselck.unlock();
}
}int test_unique_lock_2()
{std::thread threads[10];// spawn 10 threads:for (int i = 0; i<10; ++i)threads[i] = std::thread(print_thread_id, i + 1);for (auto& th : threads) th.join();return 0;
}//
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/mutex/
namespace {
class MyMutex : public std::mutex {int _id;
public:MyMutex(int id) : _id(id) {}int id() { return _id; }
};MyMutex mtx3(101);void print_ids(int id) {std::unique_lock<MyMutex> lck(mtx3);// unique_lock::mutex: Returns a pointer to the managed mutex objectstd::cout << "thread #" << id << " locked mutex " << lck.mutex()->id() << '\n';
}
}int test_unique_lock_3()
{std::thread threads[10];// spawn 10 threads:for (int i = 0; i<10; ++i)threads[i] = std::thread(print_ids, i + 1);for (auto& th : threads) th.join();return 0;
}//
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/operator=/
namespace {
std::mutex mtx4; // mutex for critical sectionvoid print_fifty(char c) {std::unique_lock<std::mutex> lck; // default-constructed// unique_lock::operator=: Replaces the managed mutex object by the one in x, including its owning statelck = std::unique_lock<std::mutex>(mtx4); // move-assignedfor (int i = 0; i<50; ++i) { std::cout << c; }std::cout << '\n';
}
}int test_unique_lock_4()
{std::thread th1(print_fifty, '*');std::thread th2(print_fifty, '$');th1.join();th2.join();return 0;
}///
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/operator_bool/
namespace {
std::mutex mtx5; // mutex for critical sectionvoid print_star() {std::unique_lock<std::mutex> lck(mtx5, std::try_to_lock);// print '*' if successfully locked, 'x' otherwise:// unique_lock::operator bool: Return whether it owns a lockif (lck)std::cout << '*';elsestd::cout << 'x';
}
}int test_unique_lock_5()
{std::vector<std::thread> threads;for (int i = 0; i<500; ++i)threads.emplace_back(print_star);for (auto& x : threads) x.join();return 0;
}///
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/owns_lock/
namespace {
std::mutex mtx6; // mutex for critical sectionvoid print_star6() {std::unique_lock<std::mutex> lck(mtx6, std::try_to_lock);// print '*' if successfully locked, 'x' otherwise:// unique_lock::owns_lock: Returns whether the object owns a lock.if (lck.owns_lock())std::cout << '*';elsestd::cout << 'x';
}
}int test_unique_lock_6()
{std::vector<std::thread> threads;for (int i = 0; i<500; ++i)threads.emplace_back(print_star6);for (auto& x : threads) x.join();return 0;
}//
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/release/
namespace {
std::mutex mtx7;
int count = 0;void print_count_and_unlock(std::mutex* p_mtx) {std::cout << "count: " << count << '\n';p_mtx->unlock();
}void task() {std::unique_lock<std::mutex> lck(mtx7);++count;// unique_lock::release: Returns a pointer to the managed mutex object, releasing ownership over itprint_count_and_unlock(lck.release());
}
}int test_unique_lock_7()
{std::vector<std::thread> threads;for (int i = 0; i<10; ++i)threads.emplace_back(task);for (auto& x : threads) x.join();return 0;
}/
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/try_lock/
namespace {
std::mutex mtx8; // mutex for critical sectionvoid print_star8() {std::unique_lock<std::mutex> lck(mtx8, std::defer_lock);// print '*' if successfully locked, 'x' otherwise:// unique_lock::try_lock: Lock mutex if not locked// true if the function succeeds in locking the managed mutex object, false otherwise.if (lck.try_lock())std::cout << '*';elsestd::cout << 'x';
}
}int test_unique_lock_8()
{std::vector<std::thread> threads;for (int i = 0; i<500; ++i)threads.emplace_back(print_star8);for (auto& x : threads) x.join();return 0;
}/
// reference: http://www.cplusplus.com/reference/mutex/unique_lock/try_lock_for/
namespace {
std::timed_mutex mtx9;void fireworks() {std::unique_lock<std::timed_mutex> lck(mtx9, std::defer_lock);// waiting to get a lock: each thread prints "-" every 200ms:// unique_lock::try_lock_for: Try to lock mutex during time spanwhile (!lck.try_lock_for(std::chrono::milliseconds(200))) {std::cout << "-";}// got a lock! - wait for 1s, then this thread prints "*"std::this_thread::sleep_for(std::chrono::milliseconds(1000));std::cout << "*\n";
}
}int test_unique_lock_9()
{std::thread threads[10];// spawn 10 threads:for (int i = 0; i<10; ++i)threads[i] = std::thread(fireworks);for (auto& th : threads) th.join();return 0;
}/
// reference: http://en.cppreference.com/w/cpp/thread/unique_lock
namespace {
struct Box {explicit Box(int num) : num_things{ num } {}int num_things;std::mutex m;
};void transfer(Box& from, Box& to, int num)
{// don't actually take the locks yetstd::unique_lock<std::mutex> lock1(from.m, std::defer_lock);std::unique_lock<std::mutex> lock2(to.m, std::defer_lock);// lock both unique_locks without deadlockstd::lock(lock1, lock2);from.num_things -= num;to.num_things += num;// 'from.m' and 'to.m' mutexes unlocked in 'unique_lock' dtors
}
}int test_unique_lock_10()
{Box acc1(100);Box acc2(50);std::thread t1(transfer, std::ref(acc1), std::ref(acc2), 10);std::thread t2(transfer, std::ref(acc2), std::ref(acc1), 5);t1.join();t2.join();return 0;
}} // namespace unique_lock_
GitHub: https://github.com/fengbingchun/Messy_Test??
總結
以上是生活随笔為你收集整理的C++11中std::unique_lock的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++中extern C的使用
- 下一篇: C++11中std::lock_guar