LoginSignup
14
12

More than 5 years have passed since last update.

C++17, C++14, C++11 に併せた std::shared_mutex, std::shared_timed_mutex, std::mutex から mutex_type, read_lock_type, write_lock_type を扱う例

Last updated at Posted at 2016-03-14

概要

C++11 から標準ライブラリーに入った std::mutex から C++14 では std::shared_timed_mutex 、 C++17(予定)では std::shared_mutex が追加される事で、 READ アクセス向けと WRITE アクセス向けにロックレベルを制御できるようになりました。

そこで、翻訳環境の C++ 規格の対応に応じて READ / WRITE 向けのロックを使い分ける簡単なコード例を示したいと思います。

  • usagi/mutex.hxx
#pragma once

#if __cplusplus >= 201402
  #include <shared_mutex>
#else
  #include <mutex>
#endif

namespace usagi
{
  namespace mutex
  {
#if __cplusplus > 201402
    // C++17
    using read_write_mutex_type = std::shared_mutex;
    using read_lock_type = std::shared_lock< read_write_mutex_type >;
    using write_lock_type = std::lock_guard< read_write_mutex_type >;
#elif __cplusplus == 201402
    // C++14
    using read_write_mutex_type = std::shared_timed_mutex;
    using read_lock_type = std::shared_lock< read_write_mutex_type >;
    using write_lock_type = std::lock_guard< read_write_mutex_type >;
#elif __cplusplus >= 201103
    // C++11
    using read_write_mutex_type = std::mutex;
    using read_lock_type = std::lock_guard< read_write_mutex_type >;
    using write_lock_type = std::lock_guard< read_write_mutex_type >;
#else
    #error not supported
#endif
  }
}

使い方

class my_example_type
{
  my_something_type                   my_something;
  usagi::mutex::read_write_mutex_type my_mutex_for_something;

public:

  auto get_something_sum_of_xyz()
  {
    usagi::mutex::read_lock_type read_lock( my_mutex_for_something );
    return my_something.x + my_something.y + my_something.z;
  }

  auto set_something_sum_of_xyz( const somevalue_type x, const somevalue_type y, const somevalue_type z )
  {
    usagi::mutex::write_lock_type write_lock( my_mutex_for_something );
    my_something.x = x;
    my_something.y = y;
    my_something.z = z;
  }
}

Reference

14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12