A very simple locked_value

I noticed that boost (or more specifically boost::thread) doesn’t directly support the notion of a value (of any type) that can be read and written to by multiple threads. So I used boost::mutex and boost::lock_guard to write one:

#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <fcppt/noncopyable.hpp>

template<typename T>
class locked_value
{
FCPPT_NONCOPYABLE(locked_value)
private:
	typedef
	boost::mutex
	lockable;

	typedef
	boost::lock_guard<lockable>
	lock;
public:
	typedef
	T
	value_type;

	explicit
	locked_value(
		value_type const &_value)
	:
		value_(
			_value)
	{
	}

	explicit
	locked_value()
	{
	}

	value_type const
	value() const
	{
		lock lock_(
			mutex_);
		return value_;
	}

	void
	value(
		value_type const &t)
	{
		lock lock_(
			mutex_);
		value_ = t;
	}
private:
	value_type value_;
	mutable lockable mutex_;
};

Notice the usage of the mutable specifier for the mutex_ variable, one of its few smart uses. Also note that I used the noncopyable macro from fcppt, which is “cleaner” than deriving from boost::noncopyable and can even be implemented using the deleted operators from C++0x (although that’s currently not the case).

Here’s a little test program just to show how it is used (assuming you saved the above code in a file locked_value.hpp):

#include "locked_value.hpp"
#include <sge/time/timer.hpp>
#include <sge/time/second.hpp>
#include <sge/time/millisecond.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <iostream>

namespace
{
void
sidethread(
	locked_value<int> &v)
{
	std::cout << "Changing value\n";

	sge::time::timer timer(
		sge::time::second(1));

	while (true)
		if (timer.update_b())
			v.value(
				v.value()+1);
}
}

int main()
{
	locked_value<int> my_int(
		0);
	boost::thread tsidethread(
		boost::bind(
			&sidethread,
			boost::ref(
				my_int)));

	sge::time::timer timer(
		sge::time::millisecond(
			100));
	while (true)
	{
		if (timer.update_b())
			std::cout << my_int.value() << '\n';
	}
}

As you can see, you need sge for this. I used it because it provides a very handy timer class.

Advertisements
This entry was posted in Uncategorized and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s