Reputation: 1597
I have a problem with C++ 11 future/promise. The following code works fine:
string s = "not written";
void write(promise<void>&& writePromise)
{
cout << "\nwrite()" << endl;
this_thread::sleep_for(chrono::seconds(1));
s = "written";
writePromise.set_value();
}
void read(future<void>&& readFut)
{
cout << "read(), waiting..." << flush;
readFut.wait();
cout << "\ns: '" << s << "'" << endl;
}
int main()
{
promise<void> writePromise;
future<void> writeFuture = writePromise.get_future();
thread tWrite(write, move(writePromise));
thread tRead(read, move(writeFuture));
tWrite.join();
tRead.join();
}
But once I change main() to this:
int main()
{
promise<void> writePromise;
thread tWrite(write, move(writePromise));
thread tRead(read, move(writePromise.get_future()));
tWrite.join();
tRead.join();
}
I get the error:
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: No associated state
Aborted (core dumped)
This exception is supposed to be thrown if you call get_future() twice on the same promise.
But all I did was just passing writePromise.get_future() to a function, so I don;t see how I call it twice.
Can someone please help?
Upvotes: 10
Views: 13619
Reputation: 51
My first oops is related with your move semantics approach
Once you writes move(writePromise)
the promise access should be avoided because the local var has been "transferred" to the thread according my understanding
My main lesson with the std::move
could be summarized as
since now i pass my enclosed var ownership to the called symbol
So, any posterior reference it's usually marked as invalid
IHTH
Upvotes: 0
Reputation: 4703
You moved writePromise
before generating future from it. This is because the thread takes ownership over the promise by value.
To fix it - first obtain future and only then forward the promise.
Upvotes: 5