c++ - 《C++ Concurrency In Action》中的可中断线程示例

标签 c++ multithreading interrupt

《C++ Concurrency In Action》在Chapter 9.2 Interrupting thread中实现了一个可中断线程。 程序 list 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();
}

按照书上的说法,这个函数引入了下面的问题:

If the thread is interrupted after the initial call to interruption_point(), but before the call to wait(), then it doesn’t matter whether the condition variable has been associated with the interrupt flag, because the thread isn’t waiting and so can’t be woken by a notify on the condition variable. You need to ensure that the thread can’t be notified between the last check for interruption and the call to wait().

第一个问题是为什么我们需要确保?因为即使 线程在初始调用 interruption_point() 之后和调用 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();
}

最佳答案

  1. 如果另一个线程在该线程到达wait() 之前调用了notify(),则该线程将不会收到该通知,并将永远等待另一个。

  2. wait_for 不会永远等待。

关于c++ - 《C++ Concurrency In Action》中的可中断线程示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35600851/

相关文章:

java - Thread.sleep 也阻塞其他线程,在其他方法上工作,以及在同步方法内部调用自身

java - 静态初始化程序和静态同步方法锁定问题

Rust 编译器对中断的支持

java - 我应该调用 `executorService.shutdown` 和 `executorService.awaitTermination` 吗?

c++ - 我的 try catch 零除法有问题吗?

c++ - 标准库中是否有与 Rust 的 `std::mem::drop` 等效的 C++?

multithreading - 什么是互斥体?

c++ - 具有常量字符串的 Gtk::TextView

c++ - 如何渲染一个看似无限大的平面?

c - 向预分频硬件定时器添加偏移量时,如何避免这种差一错误?