最終更新日時(UTC):
が更新

履歴 編集

function template
<mutex>

std::unique_lock::try_lock_until(C++11)

template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);

概要

タイムアウトする絶対時間を指定してロックの取得を試みる

テンプレートパラメータ制約

  • Mutex型が、try_lock_until()メンバ関数をサポートするミューテックス型であること
  • chrono::is_clock_v<Clock>trueであること (C++20)

効果

pm->try_lock_until(abs_time);

pmはメンバ変数として保持している、ミューテックスオブジェクトへのポインタ

事後条件

owns_lock()の値が、pm->try_lock_until(abs_time)の戻り値になること

戻り値

pm->try_lock_until(abs_time)の戻り値が返る

例外

この関数は、pm->try_lock_until() 関数内で投げられうるあらゆる例外を投げる可能性がある。

そのほかに、以下のerror conditionを持つsystem_error例外オブジェクトを送出する可能性がある:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <system_error>

class X {
  std::timed_mutex mtx_;
  int value_ = 0;
public:
  // メンバ変数value_への書き込みを排他的にする
  void add_value(int value)
  {
    std::unique_lock<std::timed_mutex> lk(mtx_, std::defer_lock);

    namespace chrono = std::chrono;
    chrono::system_clock::time_point tp = chrono::system_clock::now();

    // ロックの取得を試みる(3秒後にタイムアウト)
    if (!lk.try_lock_until(tp + chrono::seconds(3))) {
      // ロックの取得に失敗
      std::error_code ec(static_cast<int>(std::errc::device_or_resource_busy), std::generic_category());
      throw std::system_error(ec);
    }
    value_ = value;
  }
};

int main()
{
  X x;

  std::thread t1([&x]{ x.add_value(1); });
  std::thread t2([&x]{ x.add_value(2); });

  t1.join();
  t2.join();
}

出力

バージョン

言語

  • C++11

処理系

  • Clang: ??
  • GCC: 4.7.0
  • ICC: ??
  • Visual C++: 2012, 2013, 2015
    • 2012, 2013は、例外の節で説明しているsystem_errorを投げる処理が実装されていない。

参照