在线程退出时通知服务员

Notify Waiters at Thread Exit

考虑以下示例。假设你有一个生产者和 N 个消费者在等待数据。您不仅希望在数据准备就绪时通知消费者,而且希望在生产者因某种原因(错误或中断点)终止时通知消费者。在后一种情况下,读者也应该终止。

// Globals
boost::shared_future<void> future;
boost::condition_variable_any cv;

// Producer
auto producer = [&](){
    boost::this_thread::at_thread_exit([&cv] () { cv.notify_all(); });
    while (true) {
            boost::this_thread::interruption_point(); // might throw
            // ...
            cv.notify_all();
    }
};   
boost::packaged_task<void> pkg{producer};
future = pkg.get_future();
thread = boost::thread{std::move(pkg)}; // start

// Reader
while (true) {
        // ...
        // will the future be ready after the producer has been interrupted?
        cv.wait(lock_, [&ready, &future]() { return ready || future.is_ready(); });
        if (future.is_ready()) {
            future.get(); // throw, whatever has been thrown by the producer
            return;
        }
        // consume, etc...
}

以上保证有效吗?我想避免引入布尔标志或 - 更好 - 另一个新的 promise/future 对来通知并让读者知道生产者退出的原因。

基本上我不确定当读者收到boost::this_thread::at_thread_exit注册的函数通知时,与packaged_task关联的未来是否可以被视为准备就绪。这将简化我的代码(而不是将新的承诺传递给生产者线程)。如果你有更好的想法,请告诉我。

是的,这会起作用。

特别是

Basically I am not sure if the future associated with the packaged_task can be considered ready when the readers are notified by the function registered with boost::this_thread::at_thread_exit

他们可以。 packaged_task 是线程函数。当 thread_proxy implementation from Boost Thread 执行 tls_destructor (其中包括 at_thread_exit 钩子)时, packaged_task 已经返回并且承诺已经实现 -> 共享未来准备就绪.