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.