• 14
• 12
• 9
• 10
• 9

# Promise and Future with shared_ptr safety

This topic is 1669 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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;

};

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;
}

{
}

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;
}
};


Any help is very much appreciated.

##### 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.