lundi 6 juillet 2020

std::future_error: No associated state

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?

Aucun commentaire:

Enregistrer un commentaire