https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60966
--- Comment #23 from Jonathan Wakely <redi at gcc dot gnu.org> --- (In reply to Hideaki Kimura from comment #22) > Ah, you are right, set_value() might have context switch after signaling > before exitting. Or even before signalling (a waiting thread could check if the shared state is ready between the value being set and the condvar signal) > ... ah, and that's why what Thomas initially posted could also see a hang. > { // copy-paste again to refresh memory, with some simplification > std::promise<void> promise; > auto future = promise.get_future(); > std::async or thread ( {promise.set_value();}); > future.get(); > } > > The user of std::promise must make sure the asynchronous thread has surely > exitted at least from promise.set_value() before std::promise gets out of > scope. > promise/future is a handy way to synchronize between threads, but to use it > one must protect it with thread synchronization..? That's quite tedious. If you give references to local variables to other threads then you need to be careful about lifetimes, but this code is reasonable and should work. > I've just seen the patch as of writing this comment. I guess it solves the > issue? Yes, it should solve the problem, by incrementing the reference count on the shared state temporarily, until the set_value() call has completed.