Boost Thread - 如何确认中断

时间:2011-09-06 07:55:52

标签: c++ interrupt boost-thread

我有阻塞任务,将由find_the_question()函数执行。但是,我不希望线程执行此函数需要超过10秒。因此,如果需要超过10秒,我想通过清理所有资源来关闭该线程。

我尝试为此编写代码,但是如果线程占用时间超过10秒,我无法在find_the_question()函数中获得中断。你能告诉我我做错了吗?

void find_the_question(std::string value)
{
    //allocate x resources
    try{
        //do some process on resources
            sleep(14);
        //clean resources
    }
    catch(boost::thread_interrupted const& )
    {
        //clean resources
        std::cout << "Worker thread interrupted" << std::endl;
    }
}

int main()
{
        boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(10000);
        std::cout << "In main" << std::endl;
        boost::thread t1(find_the_question, "Can you block me");

        t1.interrupt();
        if (t1.timed_join(timeout))
        {
          //finished
          std::cout << "Worker thread finished" << std::endl;
        }
        else
        {
          //Not finished;
          std::cout << "Worker thread not finished" << std::endl;
        }

        std::cout << "In main end" << std::endl;
}

输出: 如果t1需要10秒以上才能完成,我将得到以下控制台输出。

std::cout << "In main" << std::endl;
std::cout << "Worker thread not finished" << std::endl;
std::cout << "In main end" << std::endl;

然而,我期待以下输出

std::cout << "In main" << std::endl;
std::cout << "Worker thread interrupted" << std::endl;
std::cout << "Worker thread not finished" << std::endl;
std::cout << "In main end" << std::endl;
你可以告诉我我做错了什么。

提前致谢

1 个答案:

答案 0 :(得分:27)

对于使用boost :: thread :: interrupt(),你必须使用boost :: thread :: sleep()才能工作。

  

可以通过调用interrupt()成员来中断正在运行的线程   相应的boost :: thread对象的功能。当。。。的时候   中断的线程接下来执行指定的中断之一   点(或当它在执行一个时当前被阻止)   中断启用,然后boost :: thread_interrupted异常将   被抛断在被打断的线程中。如果没有被抓住,这将导致   中断线程的执行终止。和任何一样   其他异常,堆栈将被解除,而析构函数则为   将执行自动存储持续时间的对象

预定义的中断点:

  

以下功能是中断点,将抛出   如果为当前启用中断,则boost :: thread_interrupted   线程,并为当前线程请求中断:

boost::thread::join()
boost::thread::timed_join()
boost::condition_variable::wait()
boost::condition_variable::timed_wait()
boost::condition_variable_any::wait()
boost::condition_variable_any::timed_wait()
boost::thread::sleep()
boost::this_thread::sleep()
boost::this_thread::interruption_point()