概要
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;
}
}