Skip to content

Latest commit

 

History

History
97 lines (76 loc) · 2.63 KB

mutex.md

File metadata and controls

97 lines (76 loc) · 2.63 KB

mutex

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

概要

mutexは、スレッド間で使用する共有リソースを排他制御するためのクラスである。lock()メンバ関数によってリソースのロックを取得し、unlock()メンバ関数でリソースのロックを手放す。

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

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++11
(destructor) デストラクタ C++11
operator=(const mutex&) = delete; 代入演算子 C++11
lock ロックを取得する C++11
try_lock ロックの取得を試みる C++11
unlock ロックを手放す C++11
native_handle ミューテックスのハンドルを取得する C++11

メンバ型

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

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

class X {
  std::mutex mtx_;
  std::vector<int> data_;
public:
  // vectorオブジェクトへのアクセスを排他的にする
  void add_value(int value)
  {
    std::lock_guard<std::mutex> lock(mtx_);
    data_.push_back(value);
  }

  void print()
  {
    for (int x : data_) {
      std::cout << x << std::endl;
    }
  }
};

int main()
{
  X x;

  std::thread t1([&x]{ x.add_value(1); });
  std::thread t2([&x]{ x.add_value(2); });

  t1.join();
  t2.join();

  x.print();
}
  • std::mutex[color ff0000]
  • data_.push_back[link /reference/vector/vector/push_back.md]

出力

1
2

バージョン

言語

  • C++11

処理系

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

参照