我们的程序中经常会用到线程来执行某些异步操作,而有些时候我们的线程执行的函数是这个样子的:
void ThreadBody()
{
while( true )
{
std::cout << "Processing..." << std::endl;
Sleep(1000);
}
} 那么,从理论上讲,这个线程将永远的执行下去,直到这个线程所属的进程运行完毕为止。注意,即使这个线程函数是某个类的成员函数,即使我们创建的,与该线程绑定的boost::thread对象是这个类的成员变量,当这个类被析构的时候,这个线程是仍然在运行的。而当该线程继续访问该类的成员变量或函数的时候,操作系统将抛出异常。这是因为该类(包括其成员变量、函数代码段)所分配的存储空间已经被释放掉了,该线程没有权限再访问这些地址空间。
所以,我们需要一种方法来终结这样子的线程。下面介绍boost::thread的一种终结这种线程的方法,当然该方法不唯一:
#include<iostream>
using namespace std;
#include<boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace boost;
typedef boost::thread CThread;
CThread* pThread = NULL;
void ThreadProc()
{
cout << "线程开始运行" << endl;
try{
while(true){
//手动在线程中加入中断点,中断点不影响其他语句执行
this_thread::interruption_point();
this_thread::sleep(posix_time::seconds(10));
//cout << "处理中······" << endl;
}
}
catch(...){
cout << "线程被中断!" << endl;
}
cout << "线程结束并退出" << endl;
}
void CreateThread(){
pThread = new CThread(ThreadProc);
cout << "新创建的线程ID为:" << pThread->get_id() << endl;
}
void DestoryThread(){
if(pThread == NULL) return;
cout << "被中断的线程ID为:" << pThread->get_id() << endl;
//向线程发送中断请求
pThread->interrupt();
//等待直到线程执行结束
pThread->join();
delete pThread; pThread = NULL;
}
void main()
{
CreateThread();
this_thread::sleep(posix_time::seconds(3));
DestoryThread();
}
那么这样就可以正常的结束这个线程了。

当然也可以采用在线程中添加标记变量的方法,比如一个bool型的变量。通过控制这个变量也可以达到线程开关的作用。
本文介绍了一种使用boost::thread库来终止无限循环线程的方法。通过在线程中加入中断点,可以实现线程的正常关闭,避免了因类析构而导致的异常问题。
865

被折叠的 条评论
为什么被折叠?



