public member function
<mutex>

std::timed_mutex::try_lock_for

template <class Rep, class Period>  bool try_lock_for (const chrono::duration<Rep,Period>& rel_time);
嘗試鎖定一段時間
嘗試鎖定timed_mutex,最多阻塞rel_time的時間
  • 如果timed_mutex當前未被任何執行緒鎖定,則呼叫執行緒鎖定它(從此時開始,直到呼叫其成員unlock,該執行緒擁有timed_mutex)。
  • 如果timed_mutex當前被另一個執行緒鎖定,則呼叫執行緒的執行將被阻塞,直到解鎖rel_time已過,以先發生者為準(在此期間,其他未鎖定的執行緒將繼續執行)。
  • 如果timed_mutex當前被呼叫此函式的同一執行緒鎖定,則會導致死鎖(具有未定義行為)。有關允許同一執行緒多次鎖定的定時互斥量型別,請參閱recursive_timed_mutex

timed_mutex的所有鎖定解鎖操作都遵循單一的全域性順序,所有可見效果鎖定操作和同一物件上的先前解鎖操作之間同步。

引數

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

返回值

如果函式成功為執行緒鎖定timed_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
30
// timed_mutex::try_lock_for example
#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex

std::timed_mutex mtx;

void fireworks () {
  // waiting to get a lock: each thread prints "-" every 200ms:
  while (!mtx.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";
  mtx.unlock();
}

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 秒後,行長度可能略有不同)

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


資料競爭

timed_mutex 物件被作為原子操作訪問/修改(不會導致資料競爭)。

異常安全

如果timed_mutex當前被呼叫執行緒鎖定,則會導致未定義行為
否則,它提供與duration 物件上的操作相同的保證(對於<chrono> 中的型別例項化,這是無丟擲保證)。

另見