public member function
<mutex>

std::mutex::try_lock

bool try_lock();
如果互斥量未被鎖定,則鎖定互斥量
嘗試鎖定 互斥量,不阻塞
  • 如果 互斥量 當前未被任何執行緒 *鎖定*,則呼叫執行緒將其 *鎖定*(從現在開始,直到其成員 unlock 被呼叫,該執行緒才 *擁有* 互斥量)。
  • 如果 互斥量 當前被另一個執行緒鎖定,該函式將失敗並返回 false,而不阻塞(呼叫執行緒繼續執行)。
  • 如果 互斥量 當前被呼叫此函式的同一執行緒鎖定,將導致 *死鎖*(具有 *未定義行為*)。有關允許同一執行緒多次鎖定的 *互斥量型別*,請參閱 recursive_mutex

當沒有其他執行緒 *鎖定* 互斥量 時,此函式可能會出現虛假失敗,但在這些情況下重複呼叫最終會成功。

互斥量 的所有 *鎖定* 和 *解鎖* 操作都遵循單一的總體順序,所有 *可見效果* 都在 *鎖定操作* 和同一物件上之前的 *解鎖操作* 之間同步。

引數



返回值

如果函式成功為執行緒 *鎖定* 互斥量,則返回 true
否則返回 false

示例

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
// mutex::try_lock example
#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 ()
{
  std::thread threads[10];
  // spawn 10 threads:
  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;
}

可能的輸出(可能為 1 到 100000 之間的任何計數)

80957 successful increases of the counter.


資料競爭

互斥量 物件作為 *原子操作* 被訪問/修改(不會導致資料爭用)。

異常安全

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

另見