|
Boost : |
Subject: [boost] [RFC] thread::access_monitor
From: Gregory Petrosyan (gregory.petrosyan_at_[hidden])
Date: 2009-01-10 11:19:37
I would like to hear your comments on the idea behind access_monitor
template, which ensures (at compile-time) that data, protected by it,
can be accessed only with associated lock held. It can be useful when
you want to expose all the native interface of your data type (STL
container, for example): in such a case, using ordinary monitor
pattern is almost impossible.
Example usage:
typedef access_monitor<data_type, mutex_type> data_access_monitor;
void f(data_access_monitor const& d)
{
data_access_monitor::value_type const* data;
data_access_monitor::lock_type lock;
boost::tie(data, lock) = d.const_lock();
// do something with data here
}
Code:
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
template <typename T, typename Lockable>
struct access_monitor
{
typedef T value_type;
typedef boost::unique_lock<Lockable> lock_type;
private:
typedef boost::detail::thread_move_t<lock_type> lock_move_type;
public:
boost::tuple<value_type const*, lock_move_type> const_lock() const
{
lock_type lock(mutex_);
return boost::make_tuple(&data_, lock.move());
}
boost::tuple<value_type*, lock_move_type> lock()
{
lock_type lock(mutex_);
return boost::make_tuple(&data_, lock.move());
}
private:
// mutex_ is guaranteed to be locked when you access data_
mutable Lockable mutex_;
T data_;
};
Sorry for draft-quality code (however, something like
the above compiles with MSVC 9).
Please CC me, because I am not subscribed.
Gregory
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk