• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    function template
    <mutex>

    std::timed_mutex::try_lock_for

    template <class Rep, class Period>
    bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
    

    概要

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

    要件

    この関数を呼び出したスレッドが、ミューテックスの所有権を保持していないこと。

    効果

    rel_timeパラメータで指定された相対時間の間、ミューテックスの所有権取得を試みる。

    所有権が取得できるまで、もしくはrel_time時間が経過するまでこの関数はブロッキングする。

    rel_timerel_time.zero()より小さい場合、この関数はtry_lock()と同じ効果をもち、ブロッキングせずにミューテックスの所有権取得を試みる。

    戻り値

    所有権が取得できた場合はtrueを返す。

    rel_timeパラメータで指定された相対時間の間に所有権が取得できなかった場合はタイムアウトとなり、falseを返す。

    例外

    • C++11 : 投げない
    • C++14 : 時計クラス、time_pointクラス、durationクラスの構築が例外を送出する場合、この関数はそれらの例外を送出する。

    備考

    この関数の実装が、ミューテックスの所有権を保持しているスレッドがひとつもない場合でも、所有権の取得に失敗する可能性がある。

    #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)
      {
        // ロックの取得を試みる(3秒でタイムアウト)
        if (!mtx_.try_lock_for(std::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;
        mtx_.unlock();
      }
    };
    
    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

    処理系

    参照