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

履歴 編集

function
<mutex>

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

bool try_lock();

概要

ロックの取得を試みる

要件

Mutex型が、try_lock()メンバ関数をサポートするミューテックス型であること

効果

pm->try_lock();

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

事後条件

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

戻り値

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

例外

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

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

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

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

    if (!lk.try_lock()) {
      // ロックの取得に失敗
      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();
}

出力

terminate called after throwing an instance of 'std::system_error'
  what():  Device or resource busy

バージョン

言語

  • C++11

処理系

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

参照