boost :: thread terminates way

Blog Reference:  https://www.cnblogs.com/lidabo/p/3796554.html

while (1) where

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

So, in theory, this thread will go on forever execution until the thread belongs processes to run. Note that even if the thread function is a member of a class, even though we created, bound with the thread boost :: thread object is a member variable of the class when the class destructor is, this thread is still in the run. And when a member variable or function when the thread continue to visit the class, the operating system will throw an exception. This is because the class (including its member variables, functions, code segments) allocated storage space has been freed up, and then the thread does not have permission to access the address space.

 Strategy 1: thread set breakpoints 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;
	/ ** can determine the thread to exit or Destroy function first exit through the statement * /
	}

	:: COUT << STD "Leaving Thread" STD :: << endl; 
}

void the Create () 
{ 
	AThread Thread :: = Boost (Boost :: the bind (& threadFucntion)); 
	STD :: COUT << "Thread ID:" < <AThread.get_id () :: STD << endl; 
} 

void the Destroy () 
{ 
	STD :: COUT << "Interrupt Thread with ID:" << AThread.get_id () :: STD << endl; 

	/ * 
	* to thread sends an interrupt request 
	* / 
	AThread.interrupt (); 
	std :: cout << "Joining the thread ..." << std :: endl; 

	/ * 
	* the Join function, is to wait until the end of the thread execution; time to increase, but Destroy function can not guarantee quit before the end of the thread is 
	* / 
	AThread.join (); 

	/ * 
	* may determine the thread through the first exit statement or Destroy function to exit 
	* / 
	std :: cout <<"Leave Destroy Function." << std::endl;
}

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

	getchar();
	return 0;
}

Then this can be the normal end of this thread. Of course, a method of adding a flag variable in a thread may also be employed, such as a type of the bool variable. By controlling this variable effect can also be achieved in a thread switch.

Guess you like

Origin www.cnblogs.com/flyinggod/p/12093470.html