2009-12-25 85 views
3

我有這個測試用例在這裏編譯與g ++ theFile.cc -lboost_thread。 運行程序時,它似乎掛在了連接命令處。我不完全確定爲什麼。這就像interrupt_point()函數沒有從主線程獲取加入請求。boost線程和加入

#include <iostream> 
#include <stdio.h> 
#include <signal.h> 
#include <fstream> 
#include <boost/thread.hpp> 

using namespace std; 


////////////////////////////////// 

    class SerialnIMU { 
    public: 
    ~SerialnIMU(); 

    void start(); 
    void stop(); 
    private: 
    boost::thread readThread; 

    class SerialReader { 
    public: 

     void operator()(); 
    private: 
    }; 
    }; 

//////////////////////////////// 


SerialnIMU::~SerialnIMU() { 
    stop(); 
} 

void SerialnIMU::start() { 
    readThread = boost::thread(SerialReader()); 
    cout<<"Created: "<<readThread.get_id()<<endl; 
} 

void SerialnIMU::stop() { 
    cout<<"Join: "<<readThread.get_id()<<endl; 
    cout<<"Joining serial thread..."<<endl; 
    readThread.join(); 
    cout<<"Done."<<endl; 
} 

//////////////////////serial thread////////////////// 

void SerialnIMU::SerialReader::operator()() { 
    cout<<"Serial reading thread started..."<<endl; 
    try { 
    while(true) { 
     boost::this_thread::interruption_point(); 
    } 
    } catch(...) { 
    cout<<"exception was thrown."<<endl; 
    } 
    cout<<"Serial reading thread stopped."<<endl; 
} 


int main(int argc, char **argv) { 

    SerialnIMU imu; 

    imu.start(); 
    imu.stop(); 
    return 0; 
} 

感謝您的閱讀。

編輯:另外,如果去掉while循環程序乾淨地退出......升壓版本1.39.0

回答

2

看來您的停止功能實際上不會中斷線程。調用join並不意味着中斷,相反,如果您希望中斷而不是等待正常終止,則必須通過在加入之前調用.interrupt()來顯式執行。

1

一個線程可以捕獲中斷異常,並繼續處理下去。如果中斷是最終的,那麼這個異常就不會被捕獲,或者你可以捕獲並停止處理,或者你可以使用像TerminateThread或pthread_cancel這樣的更具破壞性的東西,這些東西可能並不總是會做所有的清理工作。

請注意,線程可能會禁用boost :: this_thread :: disable_interruption中斷。

+0

你的意思是,如果我們沒有發現中斷異常,那麼它肯定會停止? – 2014-05-07 10:48:48