Skip to content

Latest commit

 

History

History
115 lines (92 loc) · 3.78 KB

timed_mutex.md

File metadata and controls

115 lines (92 loc) · 3.78 KB

timed_mutex

  • mutex[meta header]
  • std[meta namespace]
  • class[meta id-type]
  • cpp11[meta cpp]
namespace std {
  class timed_mutex;
}

概要

timed_mutexは、スレッド間で使用する共有リソースを排他制御するためのクラスであり、ロック取得のタイムアウト機能をサポートする。lock()メンバ関数によってリソースのロックを取得し、unlock()メンバ関数でリソースのロックを手放す。

このクラスのデストラクタは自動的にunlock()メンバ関数を呼び出すことはないため、通常このクラスのメンバ関数は直接は呼び出さず、lock_guardunique_lockといったロック管理クラスと併用する。

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++11
(destructor) デストラクタ C++11
operator=(const timed_mutex&) = delete; 代入演算子 C++11
lock ロックを取得する C++11
try_lock ロックの取得を試みる C++11
try_lock_for タイムアウトする相対時間を指定してロックの取得を試みる C++11
try_lock_until タイムアウトする絶対時間を指定してロックの取得を試みる C++11
unlock ロックを手放す C++11
native_handle ミューテックスのハンドルを取得する C++11

メンバ型

名前 説明 対応バージョン
native_handle_type 実装依存のハンドル型 C++11

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

class counter {
  int count_ = 0;
  std::timed_mutex mtx_;
public:
  int add(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);
    }

    int result = count_ += value;

    mtx_.unlock();

    return result;
  }
};

void f(counter& c)
{
  try {
    std::cout << c.add(3) << std::endl;
  }
  catch (std::system_error& e) {
    std::cout << e.what() << std::endl;
  }
}

int main()
{
  counter c;

  std::thread t1([&] { f(c); });
  std::thread t2([&] { f(c); });

  t1.join();
  t2.join();
}
  • std::timed_mutex[color ff0000]
  • mtx_.try_lock_for[link timed_mutex/try_lock_for.md]
  • std::errc::device_or_resource_busy[link /reference/system_error/errc.md]
  • std::generic_category()[link /reference/system_error/generic_category.md]
  • std::system_error[link /reference/system_error/system_error.md]
  • mtx_.unlock()[link timed_mutex/unlock.md]

出力例

3
6

バージョン

言語

  • C++11

処理系

  • Clang: ??
  • GCC: 4.7.0 [mark verified]
  • ICC: ??
  • Visual C++: 2012 [mark verified], 2013 [mark verified], 2015 [mark verified]

参照