如何检查boost线程正在运行和杀死它

How to check boost thread is running and Kill it

本文关键字:运行 线程 何检查 检查 boost      更新时间:2023-10-16

在我的程序中,它启动一个boost线程,并将处理程序保持为主线程的成员。当用户按下取消按钮时,我需要检查启动的线程是否仍在运行,如果它正在运行,则需要杀死该特定线程。下面是伪代码。

作弊线程

int i =1;
boost::thread m_uploadThread = boost::thread(uploadFileThread,i);

这是用来检查线程是否仍在运行的方法,但它没有工作

boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(2);
if (this->uploadThread.timed_join(timeout)){
 //Here it should kill the thread
}

返回值true表示线程在调用超时之前完成。看起来你想要的是

if(!this->uploadThread.timed_join(timeout))

如果要停止线程,可以使用:

my_thread.interrupt();

为了使它工作,你必须在你想要线程的函数在你中断时停止的点上设置一个中断点。

注意:它自己的中断不会停止线程,它只是设置一个标志,当到达中断点时线程被中断。如果没有找到中断点,线程不停止。

你还可以处理中断异常boost::thread_interrupted,这样你就可以根据线程是否被中断来做事情。

例如,让我们假设下一个代码在线程函数中:

try
{
    //... some important code here
    boost::this_thread.interruption_poit(); // Setting interrutption point.
}
catch(boost::thread_interrupted&)
{
    // Now you do what ever you want to do when 
    // the thread is interrupted.
}