public member function
<mutex>

std::timed_mutex::try_lock_until

template <class Clock, class Duration>  bool try_lock_until (const chrono::time_point<Clock,Duration>& abs_time);
嘗試鎖定直到時間點
嘗試鎖定 timed_mutex,最多阻塞直到 abs_time
  • 如果 timed_mutex 當前未被任何執行緒鎖定,則呼叫執行緒鎖定它(從此時開始,直到其成員 unlock 被呼叫,該執行緒擁有 timed_mutex)。
  • 如果 timed_mutex 當前被另一個執行緒鎖定,則呼叫執行緒的執行將被阻塞,直到解鎖或直到 abs_time(以先到者為準,同時,其他未鎖定的執行緒繼續執行)。
  • 如果 timed_mutex 當前被呼叫此函式的同一執行緒鎖定,則會產生死鎖(具有未定義行為)。請參閱 recursive_timed_mutex 以瞭解允許同一執行緒多次鎖定的定時互斥型別

timed_mutex 的所有鎖定解鎖操作遵循單個總順序,所有可見效果鎖定操作與同一物件上的先前解鎖操作之間進行同步。

引數

abs_time
執行緒停止阻塞並放棄鎖定嘗試的時間點。
time_point 是表示特定絕對時間的物件。

返回值

如果函式成功*鎖定*該執行緒的 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
31
32
33
34
35
36
37
38
39
40
41
42
43
// timed_mutex::try_lock_until example
#include <iostream>       // std::cout
#include <chrono>         // std::chrono::system_clock
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex
#include <ctime>          // std::time_t, std::tm, std::localtime, std::mktime

std::timed_mutex cinderella;

// gets time_point for next midnight:
std::chrono::time_point<std::chrono::system_clock> midnight() {
  using std::chrono::system_clock;
  std::time_t tt = system_clock::to_time_t (system_clock::now());
  struct std::tm * ptm = std::localtime(&tt);
  ++ptm->tm_mday; ptm->tm_hour=0; ptm->tm_min=0; ptm->tm_sec=0;
  return system_clock::from_time_t (mktime(ptm));
}

void carriage() {
  if (cinderella.try_lock_until(midnight())) {
    std::cout << "ride back home on carriage\n";
    cinderella.unlock();
  }
  else
    std::cout << "carriage reverts to pumpkin\n";
}

void ball() {
  cinderella.lock();
  std::cout << "at the ball...\n";
  cinderella.unlock();
}

int main ()
{
  std::thread th1 (ball);
  std::thread th2 (carriage);

  th1.join();
  th2.join();

  return 0;
}

可能的輸出(行序可能相反,或回車符變成南瓜)
at the ball...
ride back home on carriage


資料競爭

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

異常安全

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

另見