转自:http://blog.csdn.net/anda0109/article/details/41943691
thread的成员函数interrupt()允许正在执行的线程被中断,被中断的线程会抛出一个thread_interrupted异常,
它是一个空类,不是std::exception或boost::exception的子类。thread_interrupted异常应该在线程执行函数
里捕捉和处理,如果线程不处理这个异常,那么默认会中止线程的执行。
程序运行结果如下:
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的时候会报错,