2013-03-27 103 views
1

在我的程序中,它启动一个boost线程并将处理程序作为主线程的成员。 当用户按下取消按钮时,我需要检查仍在运行的启动线程,如果它正在运行,则需要杀死该特定线程。这里是伪代码。如何检查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 
} 
+0

它这个线程在做什么? – 2013-03-27 02:21:57

+2

永不杀死你的线索,合作结束它们。 – 2013-03-27 02:23:39

+0

永不杀你的线索,合作结束它们。 (该评论需要一些并发) – Yakk 2013-03-27 02:38:46

回答

4

返回值true意味着线程前完成通话超时。看起来像你想要的是

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

非常感谢您的支持+1。如果仍在运行,你有什么想法如何结束线程? – 2013-03-27 02:48:01

+0

一般而言,您不会杀死一个线程,而是通知它结束其生命。我同意雅克在上面的评论。 – Shawnone 2013-03-27 03:26:23

+0

我想看看一个线程是否正在运行,所以我不会尝试启动第二个线程 - 而且我不想保留一个侧栏变量。你会认为会有一个API来发现boost :: thread是不是线程...... – PatchyFog 2013-09-27 23:48:53

2

为了阻止你的线程可以使用:

my_thread.interrupt(); 

为了这个工作,你必须设置一个interruption point在点你想要的线程的功能停止时你打断了。

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

你也可以处理被中断的异常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. 
} 
相关问题