Sign in to follow this  
Mussi

Promise and Future with shared_ptr safety

Recommended Posts

Hey everyone,

 

I've implemented sort of future and promise classes for my network code using a shared_ptr that holds a boolean and a value variable. These variables are set by the promise class, which is non-copyable. The future class only reads from these variables. I thought that it'd be safe to set the boolean from within the promise in thread A and concurrently read the boolean value from within the future in thread B, but apparently it's not. What happens is that sometimes the value is not set when repeatedly reading the boolean value, even though the code is called and the address of booleans match. My question is, why is this not safe and what's happening?

 

The code:

class Future
	{
		friend class Promise;

	private:
		struct FutureData
		{
			NetworkResult value;
			bool ready;

			FutureData() : ready(false) {}
		};

		std::shared_ptr<FutureData> data;

	public:
		Future()
		{
			data = std::make_shared<FutureData>();
		}

		Future(const Future& future) : data(future.data)
		{
		}

		Future& operator =(const Future& future)
		{
			data = future.data;
		}

		Future(Future&& future) : data(std::move(future.data))
		{
		}

		Future& operator =(const Future&& future)
		{
			data = std::move(future.data);
			return *this;
		}

		bool IsReady() const
		{
			return data->ready;
		}

		NetworkResult GetValue() const
		{
			return data->value;
		}
	};

	class Promise
	{
	private:
		Future future;

		Promise(const Promise&);
		Promise& operator =(const Promise&);

	public:
		Promise()
		{	
		}

		Promise(Promise&& promise) : future(std::move(promise.future))
		{
		}

		Promise& operator =(Promise&& promise)
		{
			future = std::move(promise.future);
			return *this;
		}

		Future GetFuture() const
		{
			return future;
		}

		void SetValue(NetworkResult result)
		{
			future.data->value = result;
			future.data->ready = true;
		}
	};

Any help is very much appreciated.

Share this post


Link to post
Share on other sites

Unless you tell it otherwise, a compiler is free to assume that multiple consecutive reads from the same variable will have the same result so it can do things like cache the value in a register or something similar. Since it looks like you're using C++11, one way to get around this problem is to use std::atomic for the variables that you want to share between threads. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this