類模板
<mutex>

std::lock_guard

template <class Mutex> class lock_guard;
Lock guard
一個 lock guard 是一個物件,它透過一直鎖定來管理一個 mutex object

在構造時,mutex object 會被呼叫執行緒鎖定,在析構時,mutex 會被解鎖。它是最簡單的鎖,特別適用於具有自動儲存期並在其上下文結束時銷燬的物件。透過這種方式,它保證了在丟擲異常時 mutex object 會被正確解鎖。

但請注意,lock_guard 物件不以任何方式管理 mutex object 的生命週期:mutex object 的生命週期至少應延長到鎖定它的 lock_guard 的析構。

模板引數

互斥體
一個 mutex-like type
它應該是basic lockable type,例如 mutex (有關要求,請參閱 BasicLockable)。

成員型別

成員型別定義描述
mutex_type模板引數 ( Mutex)被管理的 mutex object 型別

成員函式



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// lock_guard example
#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;
}

可能的輸出
[exception caught]
2 is even
[exception caught]
4 is even
[exception caught]
6 is even
[exception caught]
8 is even
[exception caught]
10 is even


列印的行順序可能不同。

另見