函式模板
<mutex>

std::lock

template <class Mutex1, class Mutex2, class... Mutexes>  void lock (Mutex1& a, Mutex2& b, Mutexes&... cde);
鎖住多個互斥量
鎖定所有傳入的互斥量物件,如果需要會阻塞當前執行緒。

該函式使用一系列未指定的互斥量成員 locktry_lockunlock 的呼叫來鎖定物件,確保在返回時所有物件都被鎖定(且不會發生死鎖)。

如果該函式無法鎖定所有物件(例如,因為其內部呼叫丟擲了異常),則該函式會先解鎖所有它成功鎖定的物件(如果有的話),然後才失敗。

引數

a, b, cde
要鎖定的物件。
Mutex1Mutex2Mutexes 必須是可鎖定型別

返回值



示例

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
// std::lock example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock

std::mutex foo,bar;

void task_a () {
  // foo.lock(); bar.lock(); // replaced by:
  std::lock (foo,bar);
  std::cout << "task a\n";
  foo.unlock();
  bar.unlock();
}

void task_b () {
  // bar.lock(); foo.lock(); // replaced by:
  std::lock (bar,foo);
  std::cout << "task b\n";
  bar.unlock();
  foo.unlock();
}

int main ()
{
  std::thread th1 (task_a);
  std::thread th2 (task_b);

  th1.join();
  th2.join();

  return 0;
}
請注意,在用 std::lock 呼叫替換單獨的鎖之前,如果 task_a 鎖定了 footask_b 鎖定了 bar,那麼兩者都無法獲得第二個鎖,從而導致死鎖。

可能的輸出(行順序可能不同)

task a
task b


資料競爭

引數被修改。

異常安全

提供與對引數執行的操作相同的保證級別。

另見