libcruft-util/cruft/util/thread/monitor.hpp

50 lines
1.1 KiB
C++
Raw Permalink Normal View History

/*
2018-08-04 15:14:06 +10:00
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include <functional>
#include <mutex>
#include <utility>
namespace cruft::thread {
template <typename ValueT, typename MutexT = std::mutex>
class monitor {
public:
template <typename ...Args>
monitor (Args &&...args):
m_value (::std::forward<Args> (args)...)
{ ; }
class proxy {
public:
proxy (MutexT &_mutex, ValueT &_value):
m_guard (_mutex),
m_value (_value)
{ ; }
ValueT* operator-> ()
{
return &m_value;
}
private:
::std::lock_guard<MutexT> m_guard;
ValueT &m_value;
};
auto acquire (void) { return proxy (m_mutex, m_value); }
auto operator-> () { return acquire (); }
private:
MutexT m_mutex;
ValueT m_value;
};
};