This question is very similar to a previous one here: race-condition in pthread_once()?
It is essentially the same issue - the lifetime of a std::promise
en
In direct answer to your question, the correct answer is to give the std::promise
to the thread. That way, it's guaranteed to exist as long as the thread wants it.
Under the hood, the std::future
and std::promise
have a shared state that both point to, and is guaranteed to remain available until both sides a destroyed. Conceptually, this is similar to both the promise and the future both having individual copies of a shared_ptr to the same object. This object contains the necessary underlying mechanisms to pass state, block, and other operations.
As for attempting to signal on destruction, the problem is where would this condition variable exist? The shared area is destroyed once all of the associated futures and promises are destroyed. The deadlock is occurring because the area is being destroyed while it's still being used (because the compiler is unaware another thread is still accessing the promise as it's being destroyed). Adding additional condition variables to any shared state would not help, as they also would be destroyed.