【发布时间】:2016-02-24 19:28:58
【问题描述】:
《C++ Concurrency In Action》在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();
}
按照书上的说法,这个函数引入了以下问题:
如果线程在初始调用 interrupt_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()替换为cv.wait_for():
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();
}
【问题讨论】:
-
爱你的括号:*
标签: c++ multithreading interrupt