“C++并发操作”在Chapter 9.2 Interrupting thread中实现了一个可中断的线程。Listing 9.10如下所示:
void interruptible_wait(std::condition_variable& cv,
std::unique_lock<std::mutex>& lk)
{
interruption_point();
this_thread_interrupt_flag.set_condition_variable(cv);
cv.wait(lk);
this_thread_interrupt_flag.clear_condition_variable();
interruption_point();
}根据这本书,这一功能介绍了以下问题:
如果线程在对interruption_point()的初始调用之后中断,但在调用wait()之前,那么条件变量是否与中断标志相关联并不重要,因为线程没有等待,因此不能被条件变量的通知所唤醒。您需要确保在上次检查中断和调用wait()之间不能通知线程。
的第一个问题是为什么我们need to ensure that?因为这个函数似乎运行正确,甚至the thread is interrupted after the initial call to interruption_point() and before the call to wait()。有人能告诉我这个函数将如何运行吗?是因为cv.wait(lk)在这种情况下永远不会被通知吗?
的第二个问题是Listing 9.11是如何解决这个问题的,这本书只提到了用cv.wait_for()代替cv.wait()
void interruptible_wait(std::condition_variable& cv,
std::unique_lock<std::mutex>& lk)
{
interruption_point();
this_thread_interrupt_flag.set_condition_variable(cv);
interrupt_flag::clear_cv_on_destruct guard;
interruption_point();
cv.wait_for(lk,std::chrono::milliseconds(1));
interruption_point();
}发布于 2016-02-24 11:28:58
notify()之前调用wait(),则该线程将不会收到该通知,并且将永远等待另一个通知。wait_for不会永远等下去。https://stackoverflow.com/questions/35600851
复制相似问题