template<class Clock, class Duration>
bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time);
概要
カウンティングセマフォのカウンタ値が0より大きくなるまで待機し、カウンタ値を1つ減算してからtrueを返す。
絶対時間で指定されるタイムアウトが発生した場合はfalseを返す。
説明のため、ここではカウンタ値をcounterと表記する。
効果
次のステップを繰り返す:
try_acquireを評価し、その結果がtrueならばtrueを返す。counterが0より大きくなる、または指定された絶対時間を過ぎるまで、*this上で関数呼び出しスレッドをブロッキングする。タイムアウトが発生した場合はfalseを返す。
戻り値
カウンタ値を減算できた場合はtrueを返す。タイムアウトが発生した場合はfalseを返す。
例外
この関数はタイムアウト関連の例外オブジェクト、もしくは以下のerror conditionを持つsystem_error例外オブジェクトを送出する可能性がある:
resource_unavailable_try_again: 操作対象のネイティブハンドル型が無効operation_not_permitted: スレッドにこの操作を行う権限がないinvalid_argument: 実引数が無効
例
#include <chrono>
#include <iostream>
#include <semaphore>
#include <thread>
using Clock = std::chrono::system_clock;
int main()
{
int shared_data = 0;
std::counting_semaphore sem{0};
std::thread t([&]{
// 通知を待機し、共有データから読取り
const auto tp = Clock::now() + std::chrono::seconds{5};
if (sem.try_acquire_until(tp)) {
std::cout << shared_data << std::endl;
} else {
std::cout << "(timed out)" << std::endl;
}
});
// 共有データへ書込み、通知を行う
shared_data = 42;
sem.release();
t.join();
}
出力例
42
バージョン
言語
- C++20
処理系
- Clang: 11.0 ✅
- GCC: ??
- ICC: ??
- Visual C++: ??