C++11 并發(fā)指南之std::mutex詳解
上一篇《C++11 并發(fā)指南二(std::thread 詳解) 》中主要講到了 std::thread 的一些用法,并給出了兩個(gè)小例子,本文將介紹 std::mutex 的用法。
Mutex 又稱互斥量,C++ 11中與 Mutex 相關(guān)的類(包括鎖類型)和函數(shù)都聲明在 <mutex> 頭文件中,所以如果你需要使用 std::mutex,就必須包含 <mutex> 頭文件。
<mutex> 頭文件介紹
Mutex 系列類(四種)
- std::mutex,最基本的 Mutex 類。
- std::recursive_mutex,遞歸 Mutex 類。
- std::time_mutex,定時(shí) Mutex 類。
- std::recursive_timed_mutex,定時(shí)遞歸 Mutex 類。
Lock 類(兩種)
- std::lock_guard,與 Mutex RAII 相關(guān),方便線程對(duì)互斥量上鎖。
- std::unique_lock,與 Mutex RAII 相關(guān),方便線程對(duì)互斥量上鎖,但提供了更好的上鎖和解鎖控制。
其他類型
- std::once_flag
- std::adopt_lock_t
- std::defer_lock_t
- std::try_to_lock_t
函數(shù)
- std::try_lock,嘗試同時(shí)對(duì)多個(gè)互斥量上鎖。
- std::lock,可以同時(shí)對(duì)多個(gè)互斥量上鎖。
- std::call_once,如果多個(gè)線程需要同時(shí)調(diào)用某個(gè)函數(shù),call_once 可以保證多個(gè)線程對(duì)該函數(shù)只調(diào)用一次。
std::mutex 介紹
下面以 std::mutex 為例介紹 C++11 中的互斥量用法。
std::mutex 是C++11 中最基本的互斥量,std::mutex 對(duì)象提供了獨(dú)占所有權(quán)的特性——即不支持遞歸地對(duì) std::mutex 對(duì)象上鎖,而 std::recursive_lock 則可以遞歸地對(duì)互斥量對(duì)象上鎖。
std::mutex 的成員函數(shù)
- 構(gòu)造函數(shù),std::mutex不允許拷貝構(gòu)造,也不允許 move 拷貝,最初產(chǎn)生的 mutex 對(duì)象是處于 unlocked 狀態(tài)的。
- lock(),調(diào)用線程將鎖住該互斥量。線程調(diào)用該函數(shù)會(huì)發(fā)生下面 3 種情況:(1). 如果該互斥量當(dāng)前沒有被鎖住,則調(diào)用線程將該互斥量鎖住,直到調(diào)用 unlock之前,該線程一直擁有該鎖。(2). 如果當(dāng)前互斥量被其他線程鎖住,則當(dāng)前的調(diào)用線程被阻塞住。(3). 如果當(dāng)前互斥量被當(dāng)前調(diào)用線程鎖住,則會(huì)產(chǎn)生死鎖(deadlock)。
- unlock(), 解鎖,釋放對(duì)互斥量的所有權(quán)。
- try_lock(),嘗試鎖住互斥量,如果互斥量被其他線程占有,則當(dāng)前線程也不會(huì)被阻塞。線程調(diào)用該函數(shù)也會(huì)出現(xiàn)下面 3 種情況,(1). 如果當(dāng)前互斥量沒有被其他線程占有,則該線程鎖住互斥量,直到該線程調(diào)用 unlock 釋放互斥量。(2). 如果當(dāng)前互斥量被其他線程鎖住,則當(dāng)前調(diào)用線程返回 false,而并不會(huì)被阻塞掉。(3). 如果當(dāng)前互斥量被當(dāng)前調(diào)用線程鎖住,則會(huì)產(chǎn)生死鎖(deadlock)。
下面給出一個(gè)與 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 一樣,也是一種可以被上鎖的對(duì)象,但是和 std::mutex 不同的是,std::recursive_mutex 允許同一個(gè)線程對(duì)互斥量多次上鎖(即遞歸上鎖),來(lái)獲得對(duì)互斥量對(duì)象的多層所有權(quán),std::recursive_mutex 釋放互斥量時(shí)需要調(diào)用與該鎖層次深度相同次數(shù)的 unlock(),可理解為 lock() 次數(shù)和 unlock() 次數(shù)相同,除此之外,std::recursive_mutex 的特性和 std::mutex 大致相同。
std::time_mutex 介紹
std::time_mutex 比 std::mutex 多了兩個(gè)成員函數(shù),try_lock_for(),try_lock_until()。
try_lock_for 函數(shù)接受一個(gè)時(shí)間范圍,表示在這一段時(shí)間范圍之內(nèi)線程如果沒有獲得鎖則被阻塞?。ㄅc std::mutex 的 try_lock() 不同,try_lock 如果被調(diào)用時(shí)沒有獲得鎖則直接返回 false),如果在此期間其他線程釋放了鎖,則該線程可以獲得對(duì)互斥量的鎖,如果超時(shí)(即在指定時(shí)間內(nèi)還是沒有獲得鎖),則返回 false。
try_lock_until 函數(shù)則接受一個(gè)時(shí)間點(diǎn)作為參數(shù),在指定時(shí)間點(diǎn)未到來(lái)之前線程如果沒有獲得鎖則被阻塞住,如果在此期間其他線程釋放了鎖,則該線程可以獲得對(duì)互斥量的鎖,如果超時(shí)(即在指定時(shí)間內(nèi)還是沒有獲得鎖),則返回 false。
下面的小例子說(shuō)明了 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 的關(guān)系一樣,std::recursive_timed_mutex 的特性也可以從 std::timed_mutex 推導(dǎo)出來(lái),感興趣的同鞋可以自行查閱。 ;-)
std::lock_guard 介紹
與 Mutex RAII 相關(guān),方便線程對(duì)互斥量上鎖。例子(參考):
#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 相關(guān),方便線程對(duì)互斥量上鎖,但提供了更好的上鎖和解鎖控制。例子(參考):
#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;
}
好了,本文暫時(shí)講到這里,還剩下 std::try_lock,std::lock,std::call_once 三個(gè)函數(shù)沒有講到,留在下一篇博客中講吧 ;-)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
從匯編看c++的默認(rèn)析構(gòu)函數(shù)的使用詳解
本篇文章是對(duì)c++中默認(rèn)析構(gòu)函數(shù)的使用進(jìn)行了詳細(xì)的分析介紹。需要的朋友參考下2013-05-05
string,CString,char*之間的轉(zhuǎn)化
下面是MFC/C++/C中字符類型CString, int, string, char*之間的轉(zhuǎn)換的說(shuō)明與舉例,經(jīng)常用的東西,相信對(duì)于用C/C++的朋友,還是比較有用的2013-03-03
C語(yǔ)言實(shí)現(xiàn)數(shù)獨(dú)游戲的求解
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)數(shù)獨(dú)游戲的求解,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
在Qt中使用QtWebApp搭建HTTP服務(wù)器的詳細(xì)步驟
QtWebApp是一個(gè)開源項(xiàng)目,它基于著名的Qt?Framework開發(fā),提供了一種在C++環(huán)境中構(gòu)建HTTP服務(wù)器的解決方案,這篇文章主要給大家介紹了關(guān)于在Qt中使用QtWebApp搭建HTTP服務(wù)器的詳細(xì)步驟,需要的朋友可以參考下2024-07-07
淺析C++模板類型中的原樣轉(zhuǎn)發(fā)和可變參數(shù)的實(shí)現(xiàn)
可變參數(shù)模板(variadic templates)是C++11新增的強(qiáng)大的特性之一,它對(duì)模板參數(shù)進(jìn)行了高度泛化,能表示0到任意個(gè)數(shù)、任意類型的參數(shù),這篇文章主要介紹了C++可變參數(shù)模板的展開方式,需要的朋友可以參考下2022-08-08
VS2019創(chuàng)建c++動(dòng)態(tài)鏈接庫(kù)dll與調(diào)用方法實(shí)踐
動(dòng)態(tài)鏈接庫(kù)是一個(gè)包含可由多個(gè)程序同時(shí)使用的代碼和數(shù)據(jù)的庫(kù),本文主要介紹了VS2019創(chuàng)建c++動(dòng)態(tài)鏈接庫(kù)dll與調(diào)用方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-06-06
C語(yǔ)言編程數(shù)據(jù)結(jié)構(gòu)棧與隊(duì)列的全面講解示例教程
本文介紹著重介紹數(shù)據(jù)結(jié)構(gòu)-棧和隊(duì)列的知識(shí),由于本文也設(shè)計(jì)多個(gè)動(dòng)態(tài)內(nèi)存開辟函數(shù),小伙伴們?cè)趯W(xué)習(xí)本文之前,一定一定一定要把動(dòng)態(tài)內(nèi)存開辟相關(guān)知識(shí)掌握牢固,這樣學(xué)習(xí)起本文才能事半功倍2021-10-10

