std::future_error: No associated state
Asked Answered
S

2

9

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?

Strop answered 6/7, 2020 at 19:21 Comment(0)
C
3

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.

Chromatin answered 6/7, 2020 at 19:40 Comment(0)
K
0

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

Kegler answered 22/10, 2022 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.