public member function
<mutex>

std::mutex::unlock

void unlock();
解鎖互斥量
解鎖 mutex釋放對其的所有權

如果其他執行緒當前被阻塞並嘗試鎖定此相同的 mutex,則其中一個執行緒獲得所有權並繼續執行。

mutex 的所有鎖定解鎖操作遵循單一的總順序,所有可見效果都在鎖定操作和同一物件的先前解鎖操作之間同步。

如果 mutex 當前未被呼叫執行緒鎖定,則會導致未定義行為

引數



返回值



示例

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

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

void print_thread_id (int id) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  mtx.lock();
  std::cout << "thread #" << id << '\n';
  mtx.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


資料競爭

mutex 物件的修改是原子操作(不引起資料競爭)。

異常安全

如果 mutex 當前被呼叫執行緒鎖定,則此函式永遠不會丟擲異常(無異常保證)。
否則,將導致未定義行為

另見