【问题标题】:boost::this_thread::interruption_point() doesn't throw boost::thread_interrupted& exceptionboost::this_thread::interruption_point() 不会抛出 boost::thread_interrupted& 异常
【发布时间】:2014-09-29 15:38:55
【问题描述】:

我想使用 boost::thread interrupt() 来中断一个线程。我有以下代码不会抛出 boost::thread_interrupted& 异常:

int myClass::myFunction (arg1, arg2) try{
//some code here
    do {   
        boost::this_thread::interruption_point(); 
        //some other code here
    } while (counter != 20000); 
}catch (boost::thread_interrupted&) {
    cout << "interrupted" << endl;
}

如果我将 boost::this_thread::interruption_point() 替换为 boost::this_thread::sleep( boost::posix_time::milliseconds(150)) 会抛出异常并且中断正常工作。

谁能解释为什么 boost::this_thread::interruption_point() 没有抛出预期的异常?

【问题讨论】:

  • 很可能使用 boost::this_thread::interruption_point() 在 boost::thread::interrupt() 调用之前已经退出循环。 boost::this_thread::interruption_point() 不会在任何时候阻塞,它只是一个线程可以被中断的检查点,并且 20000 不是检查此类内容的非常高的迭代次数,除非其他代码未显示需要相当长的时间才能完成。
  • 您好,感谢您的回复。当 boost::thread::interrupt() 被调用时,我仍在循环中,因为我正在打印计数器并且它还没有达到 20000。 boost::this_thread::interruption_point(); 之后的代码很长并且需要时间来完成这就是为什么我需要在某些情况下打断它。
  • 我现在意识到你不能在一个不返回的函数之前放置一个 interrupt_point 并期望中断来停止它。一旦调用了interrupt,下次再运行interrupt_point,就会抛出异常,对吗?
  • 函数返回,我的错误没有包含在提供的代码中。

标签: c++ boost interrupted-exception


【解决方案1】:

正如评论者所说,无法排除简单的竞争条件(很大程度上取决于您的架构和 CPU 负载)。添加显式睡眠“有助于”这一事实强调了这一点。

您是否在单核系统上运行?

这是一个简单的独立示例,以防您发现自己的做法有所不同。看看这个简单的测试器:

#include <iostream> 
#include <boost/thread.hpp>

struct myClass { 
    int myFunction(int arg1, int arg2);
};

int myClass::myFunction (int arg1, int arg2)
{
    int counter = 0;
    try
    {
        //some code here
        do {   
            boost::this_thread::interruption_point(); 
            //some other code here
            ++counter;
        } while (counter != 20000); 
    } catch (boost::thread_interrupted&) {
        std::cout << "interrupted" << std::endl;
    }
    return counter;
}

void treadf() {
    myClass x;
    std::cout << "Returned: " << x.myFunction(1,2) << "\n";
}

int main()
{
    boost::thread t(treadf);
    //t.interrupt(); // UNCOMMENT THIS LINE
    t.join();
}

打印出来

Returned: 20000

或者,如果您取消注释带有t.interrupt() 的行

interrupted
Returned: 0

在我的 i7 系统上。看到它Live On Coliru

【讨论】:

  • 您好,感谢您的回复。我在双核系统上运行。我阅读了您提供的示例,但我看不出这与我的代码有什么区别。
  • 我想您可以发布一个 SSCCE 来为您显示问题。也许我们可以发现一些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多