Promise and Future with shared_ptr safety

Started by
1 comment, last by Mussi 10 years, 7 months ago

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.

Advertisement

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.

Thank you SiCrane, it seems like that was it. Using std::atomic<bool> solved my problem.

This topic is closed to new replies.

Advertisement