C++11 并發(fā)指南之std::mutex詳解
上一篇《C++11 并發(fā)指南二(std::thread 詳解) 》中主要講到了 std::thread 的一些用法,并給出了兩個小例子,本文將介紹 std::mutex 的用法。
Mutex 又稱互斥量,C++ 11中與 Mutex 相關的類(包括鎖類型)和函數(shù)都聲明在 <mutex> 頭文件中,所以如果你需要使用 std::mutex,就必須包含 <mutex> 頭文件。
<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 相關,方便線程對互斥量上鎖,但提供了更好的上鎖和解鎖控制。
其他類型
- std::once_flag
- std::adopt_lock_t
- std::defer_lock_t
- std::try_to_lock_t
函數(shù)
- std::try_lock,嘗試同時對多個互斥量上鎖。
- std::lock,可以同時對多個互斥量上鎖。
- std::call_once,如果多個線程需要同時調用某個函數(shù),call_once 可以保證多個線程對該函數(shù)只調用一次。
std::mutex 介紹
下面以 std::mutex 為例介紹 C++11 中的互斥量用法。
std::mutex 是C++11 中最基本的互斥量,std::mutex 對象提供了獨占所有權的特性——即不支持遞歸地對 std::mutex 對象上鎖,而 std::recursive_lock 則可以遞歸地對互斥量對象上鎖。
std::mutex 的成員函數(shù)
- 構造函數(shù),std::mutex不允許拷貝構造,也不允許 move 拷貝,最初產生的 mutex 對象是處于 unlocked 狀態(tài)的。
- lock(),調用線程將鎖住該互斥量。線程調用該函數(shù)會發(fā)生下面 3 種情況:(1). 如果該互斥量當前沒有被鎖住,則調用線程將該互斥量鎖住,直到調用 unlock之前,該線程一直擁有該鎖。(2). 如果當前互斥量被其他線程鎖住,則當前的調用線程被阻塞住。(3). 如果當前互斥量被當前調用線程鎖住,則會產生死鎖(deadlock)。
- unlock(), 解鎖,釋放對互斥量的所有權。
- try_lock(),嘗試鎖住互斥量,如果互斥量被其他線程占有,則當前線程也不會被阻塞。線程調用該函數(shù)也會出現(xiàn)下面 3 種情況,(1). 如果當前互斥量沒有被其他線程占有,則該線程鎖住互斥量,直到該線程調用 unlock 釋放互斥量。(2). 如果當前互斥量被其他線程鎖住,則當前調用線程返回 false,而并不會被阻塞掉。(3). 如果當前互斥量被當前調用線程鎖住,則會產生死鎖(deadlock)。
下面給出一個與 std::mutex 的小例子(參考)
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_10k_increases() {
for (int i=0; i<10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main (int argc, const char* argv[]) {
std::thread threads[10];
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
std::recursive_mutex 介紹
std::recursive_mutex 與 std::mutex 一樣,也是一種可以被上鎖的對象,但是和 std::mutex 不同的是,std::recursive_mutex 允許同一個線程對互斥量多次上鎖(即遞歸上鎖),來獲得對互斥量對象的多層所有權,std::recursive_mutex 釋放互斥量時需要調用與該鎖層次深度相同次數(shù)的 unlock(),可理解為 lock() 次數(shù)和 unlock() 次數(shù)相同,除此之外,std::recursive_mutex 的特性和 std::mutex 大致相同。
std::time_mutex 介紹
std::time_mutex 比 std::mutex 多了兩個成員函數(shù),try_lock_for(),try_lock_until()。
try_lock_for 函數(shù)接受一個時間范圍,表示在這一段時間范圍之內線程如果沒有獲得鎖則被阻塞?。ㄅc std::mutex 的 try_lock() 不同,try_lock 如果被調用時沒有獲得鎖則直接返回 false),如果在此期間其他線程釋放了鎖,則該線程可以獲得對互斥量的鎖,如果超時(即在指定時間內還是沒有獲得鎖),則返回 false。
try_lock_until 函數(shù)則接受一個時間點作為參數(shù),在指定時間點未到來之前線程如果沒有獲得鎖則被阻塞住,如果在此期間其他線程釋放了鎖,則該線程可以獲得對互斥量的鎖,如果超時(即在指定時間內還是沒有獲得鎖),則返回 false。
下面的小例子說明了 std::time_mutex 的用法(參考)。
#include <iostream> // std::cout
#include <chrono> // std::chrono::milliseconds
#include <thread> // std::thread
#include <mutex> // std::timed_mutex
std::timed_mutex mtx;
void fireworks() {
// waiting to get a lock: each thread prints "-" every 200ms:
while (!mtx.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";
mtx.unlock();
}
int main ()
{
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;
}
std::recursive_timed_mutex 介紹
和 std:recursive_mutex 與 std::mutex 的關系一樣,std::recursive_timed_mutex 的特性也可以從 std::timed_mutex 推導出來,感興趣的同鞋可以自行查閱。 ;-)
std::lock_guard 介紹
與 Mutex RAII 相關,方便線程對互斥量上鎖。例子(參考):
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error
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 main ()
{
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;
}
std::unique_lock 介紹
與 Mutex RAII 相關,方便線程對互斥量上鎖,但提供了更好的上鎖和解鎖控制。例子(參考):
#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;
}
好了,本文暫時講到這里,還剩下 std::try_lock,std::lock,std::call_once 三個函數(shù)沒有講到,留在下一篇博客中講吧 ;-)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
淺析C++模板類型中的原樣轉發(fā)和可變參數(shù)的實現(xiàn)
可變參數(shù)模板(variadic templates)是C++11新增的強大的特性之一,它對模板參數(shù)進行了高度泛化,能表示0到任意個數(shù)、任意類型的參數(shù),這篇文章主要介紹了C++可變參數(shù)模板的展開方式,需要的朋友可以參考下2022-08-08
VS2019創(chuàng)建c++動態(tài)鏈接庫dll與調用方法實踐
動態(tài)鏈接庫是一個包含可由多個程序同時使用的代碼和數(shù)據(jù)的庫,本文主要介紹了VS2019創(chuàng)建c++動態(tài)鏈接庫dll與調用方法,具有一定的參考價值,感興趣的可以了解一下2024-06-06
C語言編程數(shù)據(jù)結構棧與隊列的全面講解示例教程
本文介紹著重介紹數(shù)據(jù)結構-棧和隊列的知識,由于本文也設計多個動態(tài)內存開辟函數(shù),小伙伴們在學習本文之前,一定一定一定要把動態(tài)內存開辟相關知識掌握牢固,這樣學習起本文才能事半功倍2021-10-10

