C++11中std::lock_guard的使用
互斥類的最重要成員函數是lock()和unlock()。在進入臨界區時,執行lock()加鎖操作,如果這時已經被其它線程鎖住,則當前線程在此排隊等待。退出臨界區時,執行unlock()解鎖操作。更好的辦法是采用”資源分配時初始化”(RAII)方法來加鎖、解鎖,這避免了在臨界區中因為拋出異常或return等操作導致沒有解鎖就退出的問題。極大地簡化了程序員編寫mutex相關的異常處理代碼。C++11的標準庫中提供了std::lock_guard類模板做mutex的RAII。
std::lock_guard類的構造函數禁用拷貝構造,且禁用移動構造。std::lock_guard類除了構造函數和析構函數外沒有其它成員函數。
在std::lock_guard對象構造時,傳入的mutex對象(即它所管理的mutex對象)會被當前線程鎖住。在lock_guard對象被析構時,它所管理的mutex對象會自動解鎖,不需要程序員手動調用lock和unlock對mutex進行上鎖和解鎖操作。lock_guard對象并不負責管理mutex對象的生命周期,lock_guard對象只是簡化了mutex對象的上鎖和解鎖操作,方便線程對互斥量上鎖,即在某個lock_guard對象的生命周期內,它所管理的鎖對象會一直保持上鎖狀態;而lock_guard的生命周期結束之后,它所管理的鎖對象會被解鎖。程序員可以非常方便地使用lock_guard,而不用擔心異常安全問題。
std::lock_guard在構造時只被鎖定一次,并且在銷毀時解鎖。
關于std::mutex的基礎介紹可以參考: http://blog.csdn.net/fengbingchun/article/details/73521630?
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 "lock_guard.hpp"
#include <iostream>
#include <thread>
#include <mutex>
#include <stdexcept>
#include <list>
#include <algorithm>namespace lock_guard_ {///
// reference: http://www.cplusplus.com/reference/mutex/lock_guard/
namespace {
std::mutex mtx;void print_even(int x) {if (x % 2 == 0) std::cout << x << " is even\n";else throw (std::logic_error("not even"));
}void print_thread_id(int id) {try {// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:std::lock_guard<std::mutex> lck(mtx);print_even(id);} catch (std::logic_error&) {std::cout << "[exception caught]\n";}
}
}int test_lock_guard_1()
{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/lock_guard/lock_guard/
namespace {
std::mutex mtx2; // mutex for critical sectionvoid print_thread_id2(int id) {mtx2.lock();std::lock_guard<std::mutex> lck(mtx2, std::adopt_lock);std::cout << "thread #" << id << '\n';
}
}int test_lock_guard_2()
{std::thread threads[10];// spawn 10 threads:for (int i = 0; i<10; ++i)threads[i] = std::thread(print_thread_id2, i + 1);for (auto& th : threads) th.join();return 0;
}// reference: http://en.cppreference.com/w/cpp/thread/lock_guard
namespace {
int g_i = 0;
std::mutex g_i_mutex; // protects g_ivoid safe_increment()
{std::lock_guard<std::mutex> lock(g_i_mutex);++g_i;std::cout << std::this_thread::get_id() << ": " << g_i << '\n';// g_i_mutex is automatically released when lock goes out of scope
}
}int test_lock_guard_3()
{std::cout << "main: " << g_i << '\n';std::thread t1(safe_increment);std::thread t2(safe_increment);t1.join();t2.join();std::cout << "main: " << g_i << '\n';return 0;
}//
// reference: http://www.bogotobogo.com/cplusplus/C11/7_C11_Thread_Sharing_Memory.php
namespace {
// a global variable
std::list<int> myList;// a global instance of std::mutex to protect global variable
std::mutex myMutex;void addToList(int max, int interval)
{// the access to this function is mutually exclusivestd::lock_guard<std::mutex> guard(myMutex);for (int i = 0; i < max; i++) {if ((i % interval) == 0) myList.push_back(i);}
}void printList()
{// the access to this function is mutually exclusivestd::lock_guard<std::mutex> guard(myMutex);for (auto itr = myList.begin(), end_itr = myList.end(); itr != end_itr; ++itr) {std::cout << *itr << ",";}
}
}
int test_lock_guard_4()
{int max = 100;std::thread t1(addToList, max, 1);std::thread t2(addToList, max, 10);std::thread t3(printList);t1.join();t2.join();t3.join();return 0;
}} // namespace lock_guard_
GitHub: https://github.com/fengbingchun/Messy_Test?
總結
以上是生活随笔為你收集整理的C++11中std::lock_guard的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++11中std::unique_lo
- 下一篇: TEE(Trusted Executio