public member function
<mutex>

std::unique_lock::try_lock_for

template <class Rep, class Period>  bool try_lock_for (const chrono::duration<Rep,Period>& rel_time);
在時間段內嘗試鎖定互斥量
呼叫所管理定時互斥量物件的成員函式 try_lock_for,並使用其返回值來設定擁有狀態

如果呼叫前擁有狀態已經是true,或者物件當前管理著互斥量物件,該函式將丟擲 system_error 異常。

引數

rel_time
執行緒等待獲取鎖的最長時間。
duration 是一個表示特定相對時間的物件。

返回值

如果函式成功鎖定了所管理的定時互斥量物件,則返回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
30
// unique_lock::try_lock_for example
#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex, std::unique_lock, std::defer_lock

std::timed_mutex mtx;

void fireworks () {
  std::unique_lock<std::timed_mutex> lck(mtx,std::defer_lock);
  // waiting to get a lock: each thread prints "-" every 200ms:
  while (!lck.try_lock_for(std::chrono::milliseconds(200))) {
    std::cout << "-";
  }
  // got a lock! - wait for 1s, then this thread prints "*"
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  std::cout << "*\n";
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(fireworks);

  for (auto& th : threads) th.join();

  return 0;
}

可能的輸出(大約 10 秒後,行長度可能略有不同)

------------------------------------*
----------------------------------------*
-----------------------------------*
------------------------------*
-------------------------*
--------------------*
---------------*
----------*
-----*
*


資料競爭

訪問/修改 unique_lock 物件。
所管理的定時互斥量物件被作為原子操作訪問/修改(不會導致資料競爭)。

異常安全

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

如果呼叫失敗,將丟擲system_error 異常
exception typeerror condition描述
system_errorerrc::resource_deadlock_would_occurunique_lock 物件已擁有鎖
system_errorerrc::operation_not_permittedunique_lock 物件當前未管理任何互斥量物件(因為它被預設構造移動釋放)。
如果對所管理的定時互斥量物件try_lock_for 呼叫失敗,或庫實現透過此類機制報告的任何其他條件,也會丟擲異常。

另見