溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++11 并發(fā)指南之std::mutex詳解

發(fā)布時(shí)間:2020-10-04 09:03:01 來源:腳本之家 閱讀:211 作者:Haippy 欄目:編程語言

上一篇《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ì)互斥量多次上鎖(即遞歸上鎖),來獲得對(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)未到來之前線程如果沒有獲得鎖則被阻塞住,如果在此期間其他線程釋放了鎖,則該線程可以獲得對(duì)互斥量的鎖,如果超時(shí)(即在指定時(shí)間內(nèi)還是沒有獲得鎖),則返回 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 的關(guān)系一樣,std::recursive_timed_mutex 的特性也可以從 std::timed_mutex 推導(dǎo)出來,感興趣的同鞋可以自行查閱。 ;-)

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 th2 (print_block,50,'*');
 std::thread th3 (print_block,50,'$');

 th2.join();
 th3.join();

 return 0;
}

好了,本文暫時(shí)講到這里,還剩下 std::try_lock,std::lock,std::call_once 三個(gè)函數(shù)沒有講到,留在下一篇博客中講吧 ;-)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI