boost::thread编程-线程中断(转)

原文转自 http://blog.csdn.net/anda0109/article/details/41943691

thread的成员函数interrupt()允许正在执行的线程被中断,被中断的线程会抛出一个thread_interrupted异常,它是一个空类,不是std::exception或boost::exception的子类

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>

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<<str<<++x<<std::endl;
        }
    }
    catch (boost::thread_interrupted& )//捕获线程中断异常
    {
        std::cout<<"thread interrupted!"<<std::endl;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    boost::atomic_int x(0);
    boost::thread t(to_interrupt,ref(x),"hello");
    boost::this_thread::sleep(boost::posix_time::seconds(2));//休眠2s
    t.interrupt();//要求线程中断执行
    t.join();//由于线程已经中断,所以立即返回
    getchar();
    return 0;
}

程序运行结果如下: 

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
 
 
原文地址:https://www.cnblogs.com/happykoukou/p/6986203.html