boost::thread编程-线程中断

thread的成员函数interrupt()允许正在执行的线程被中断,被中断的线程会抛出一个thread_interrupted异常,它是一个空类,不是std::exception或boost::exception的子类。thread_interrupted异常应该在线程执行函数里捕捉和处理,如果线程不处理这个异常,那么默认会中止线程的执行。

#include "stdafx.h"
#include 
#include 
#include 
#include 

boost::mutex io_mu;//io流操作锁

void to_interrupt(boost::atomic_int &x,const std::string &str)
{
	try
	{
		for(int i=0;i<5;++i)
		{
			boost::this_thread::sleep(boost::posix_time::seconds(1));//等待1s
			//Sleep(1000);//等待1s
			boost::mutex::scoped_lock lock(io_mu);//锁定io流操作
			std::cout<
程序运行结果如下:

hello1
hello2
thread interrupted!

由运行结果可知,线程在执行了两次循环之后中断执行。

上面程序中使用了boost::this_thread::sleep()函数,如果换成windows API函数Sleep(1000),重新运行,则发现线程并没有终止。读者可自行试验。

这就说明线程并不是在任何时候都可以中断的。

线程中断点:

线程并非在任何时候都可以中断的,thread库定义了若干个中断点,只有当线程执行到中断点的时候才可以被中断,一个线程可以有若干个线程中断点。

thread库定义了9个中断点,它们都是函数,如下:

thread::join();

thread::timed_join();
condition_variable::wait();
condition_variable::timed_wait();
condition_variable_any::wait();
condition_variable_any::timed_wait();
thread::sleep();

this_thread::sleep();

this_thread::interruption_point();

这些中断点的前8个都是某种形式的等待函数,表明线程在阻塞的时候可以被中断。而最后一个this_thread::interruption_point();则是一个特殊的中断点函数,它并不等待,只是起到一个标签的作用,表示线程执行到这个地方可以被中断。

注:在xp环境下使用this_thread::sleep的时候会报错,

      无法定位程序输入点GetTickCount64 在动态链接库kernel32.dll上 错误

解决方法:在stdafx.h中加 #define _WIN32_WINNT 0x0501


你可能感兴趣的:(boost学习,C/C++,C++开发)