[英]How to check boost thread is running and Kill it
In my program, it start a boost thread and keep the handler as a member of the main thread. 在我的程序中,它启动了一个Boost线程,并将处理程序保留为主线程的成员。 When user press the cancel button I need to check the started thread still running and if it is running need tho kill that specific thread.
当用户按下取消按钮时,我需要检查启动的线程是否仍在运行,如果正在运行,则需要杀死该特定线程。 here is the pseudo code.
这是伪代码。
cheating thread 作弊线
int i =1;
boost::thread m_uploadThread = boost::thread(uploadFileThread,i);
This is the method use to check if thread is still running, but it is not working 这是用于检查线程是否仍在运行但无法正常工作的方法
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(2);
if (this->uploadThread.timed_join(timeout)){
//Here it should kill the thread
}
The return value true means the thread is completed before the call times out. 返回值true表示线程在调用超时之前完成。 And looks like what you want is
看起来你想要的是
if(!this->uploadThread.timed_join(timeout))
For stop your thread you can use: 要停止线程,可以使用:
my_thread.interrupt();
in order this to work you have to set an interruption point at the point you want the thread's function stops when you interrupt. 为了这个工作,你必须设置一个断点在你想要的线程的功能点,当你中断停止。
Note: the interruption by it self don't stop the thread it just set a flag and the when an interruption point is reached the thread is interrupted. 注意:中断本身不会停止线程,它只是设置一个标志,当到达中断点时,线程将被中断。 If no interruption point is found, the thread don't stop.
如果未找到中断点,则线程不会停止。
You can also handle the interrupted exception boost::thread_interrupted
that way you can do things depending on if the thread was interrupted or not. 您还可以通过这种方式处理被中断的异常
boost::thread_interrupted
,从而可以根据线程是否被中断来执行操作。
For instance lets assume the next code is inside a thread function: 例如,假设下一个代码在线程函数内:
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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.