Non-obvious lifetime issue with std::promise and std::future

后端 未结 4 1758
[愿得一人]
[愿得一人] 2021-02-05 18:10

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

4条回答
  •  一整个雨季
    2021-02-05 18:22

    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.

提交回复
热议问题