public member function
<mutex>

std::unique_lock::unlock

void unlock();
解鎖互斥量
呼叫所管理“互斥量物件”的成員函式unlock,並將“擁有狀態”設定為false

如果呼叫前“擁有狀態”為false,則該函式將丟擲一個system_error 異常,其錯誤條件為operation_not_permitted

引數



返回值



示例

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

std::mutex mtx;           // mutex for critical section

void print_thread_id (int id) {
  std::unique_lock<std::mutex> lck (mtx,std::defer_lock);
  // critical section (exclusive access to std::cout signaled by locking lck):
  lck.lock();
  std::cout << "thread #" << id << '\n';
  lck.unlock();
}

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;
}

可能的輸出(行的順序可能不同,但它們絕不會交錯)
thread #1
thread #2
thread #3
thread #4
thread #5
thread #6
thread #7
thread #8
thread #9
thread #10


資料競爭

unique_lock”物件被修改。
所管理的“互斥量物件”被訪問和修改(作為“原子操作”,不會引起資料爭用)。

異常安全

基本保證:如果此成員函式丟擲異常,則“unique_lock”物件仍處於有效狀態。

如果呼叫失敗,將丟擲system_error 異常
異常型別錯誤條件描述
system_errorerrc::operation_not_permittedunique_lock”物件當前不管理任何“互斥量物件”(因為它被“預設構造”、“移動”或“釋放”)。
根據庫實現的不同,此成員函式還可能丟擲異常來報告其他情況。

另見