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

履歴 編集

class
<mutex>

std::timed_mutex(C++11)

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();
}

出力例

3
6

バージョン

言語

  • C++11

処理系

参照