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
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM