boost::thread 终止方式

博客参考: https://www.cnblogs.com/lidabo/p/3796554.html

while(1)情况

void threadFunction()  
{  
    while( true )  
    {  
        std::cout << "todo something..." << std::endl;  
        Sleep(1000);  
    }  
} 

那么,从理论上讲,这个线程将永远的执行下去,直到这个线程所属的进程运行完毕为止。注意,即使这个线程函数是某个类的成员函数,即使我们创建的,与该线程绑定的boost::thread对象是这个类的成员变量,当这个类被析构的时候,这个线程是仍然在运行的。而当该线程继续访问该类的成员变量或函数的时候,操作系统将抛出异常。这是因为该类(包括其成员变量、函数代码段)所分配的存储空间已经被释放掉了,该线程没有权限再访问这些地址空间。

 策略1: 线程中设置中断点  boost::this_thread::interruption_point

#include <iostream>   
#include <Windows.h>
#include <boost/thread.hpp>  
using namespace std;

boost::thread AThread;

void threadFucntion()
{
	std::cout << "Thread started." << std::endl;

	try
	{
		while (true)
		{
			/*
			* 手动在线程中加入中断点,中断点不影响其他语句执行 
			*/
			boost::this_thread::interruption_point();
			std::cout << "todo something..." << std::endl;
			Sleep(100);
		}
	}
	catch (...)
	{
		std::cout << "Interrupt exception was thrown." << std::endl;
	}

	/** 通过该语句可以判断线程先退出还是Destroy函数先退出 */
	std::cout << "Leaving thread" << std::endl;
}

void Create()
{
	AThread = boost::thread(boost::bind(&threadFucntion));
	std::cout << "thread id: " << AThread.get_id() << std::endl;
}

void Destroy()
{
	std::cout << "Interrupt thread with id: " << AThread.get_id() << std::endl;

	/*
	* 向线程发送中断请求
	*/
	AThread.interrupt();
	std::cout << "Joining thread..." << std::endl;

	/*
	* join函数,作用是等待直到线程执行结束;可不加,但不能保证退出Destroy函数前线程被终结
	*/
	AThread.join();

	/*
	* 通过该语句可以判断线程先退出还是Destroy函数先退出 
	*/
	std::cout << "Leave Destroy Function." << std::endl;
}

int main()
{
	Create();
	Sleep(1000);
	Destroy();

	getchar();
	return 0;
}

那么这样就可以正常的结束这个线程了。当然也可以采用在线程中添加标记变量的方法,比如一个bool型的变量。通过控制这个变量也可以达到线程开关的作用。

猜你喜欢

转载自www.cnblogs.com/flyinggod/p/12093470.html