• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    class
    <mutex>

    std::try_to_lock

    namespace std {
      struct try_to_lock_t { explicit try_to_lock_t() = default; };
      constexpr try_to_lock_t try_to_lock { };        // C++11
      inline constexpr try_to_lock_t try_to_lock { }; // C++17
    }
    

    概要

    try_to_lock_t型とその値try_to_lockは、遅延ロックのためのタグである。

    lock()/unlock()の呼び出しをRAIIで自動化するunique_lockクラスのコンストラクタでlock()の代わりにtry_lock()を呼び出すために使用する。

    #include <iostream>
    #include <mutex>
    
    int main()
    {
      std::mutex mtx;
      {
        std::unique_lock<std::mutex> lk(mtx, std::try_to_lock); // lock()の代わりにtry_lock()を呼び出す
        if (!lk) {
          // ロックの取得に失敗
          std::error_code ec(static_cast<int>(std::errc::device_or_resource_busy), std::generic_category());
          throw std::system_error(ec);
        }
    
        // ...共有リソースにアクセスする...
    
      } // unique_lockの破棄時にunlock()される
    }
    

    出力

    バージョン

    言語

    • C++11

    処理系

    • Clang: ??
    • GCC: 4.7.0
    • ICC: ??
    • Visual C++: 2012 , 2013 , 2015
      • 2012, 2013はconstexprが実装されていないため、代わりにtry_to_lockにはconstが修飾されている。

    参照

    • [LWG Issue 2510. Tag types should not be DefaultConstructible](https://cplusplus.github.io/LWG/issue2510