2014-10-03 148 views
1

boost :: thread interrupt()僅在第一次執行中斷點時拋出異常?我的情況如下。boost :: thread interrupt()僅在第一次執行中斷點時拋出異常?

我創建了一個boost::thread其執行functionA.functionA電話functionB並且當functionB我們調用函數threadInterrupt.functionB拋出一個boost::thread_interrupted異常,並返回執行另一斷點時functionA.我的問題是,如果一個新的boost::thread_interrupted異常將在泛函被扔。

void MyClass::function(int arg1, int arg2) try { 
    boost::thread* t = new boost::thread(boost::bind(&MyClass::functionA, this, var1, var2)); 
} catch (...) { 
    cout << "function throw an exception" << endl; 
} 

void MyClass::functionA(int arg1, int arg2) try { 
    //some code here 
    try { 
     int retVal = MyClass::functionB(var); 
     boost::this_thread::interruption_point(); 
     //some code here 
    } catch(boost::thread_interrupted&) { 
     cout << "thread interrupted in functionA" << endl; 
    } 
} catch (...) { 
    cout << "functionA throw an exception" << endl; 
} 

int MyClass::functionB(int arg1) try { 
    //some code here 
    try { 
     boost::this_thread::interruption_point(); 
     //some code here 
    } catch(boost::thread_interrupted&) { 
     cout << "thread interrupted in functionB" << endl; 
     return 0; 
    } 
    return 1; 
} catch (...) { 
    cout << "functionB throw an exception" << endl; 
    return 1; 
} 

void MyClass::threadInterrupt() { 
    if (thr!=NULL) { 
     thr->interrupt(); 
     thr->join(); 
     delete thr; 
     thr=NULL; 
    } 
} 

回答

1

你試過了嗎?看到它Live On Coliru

#include <boost/thread.hpp> 
#include <iostream> 

using namespace boost; 

int main() { 
    thread t([]{ 
      int i = 0; 
      while (true) try { 
       if (i >= 10) return; 
       while (i < 10) { 
        this_thread::sleep_for(chrono::milliseconds(200)); 
        std::cout << "processed " << i++ << "\n"; 
       } 
      } 
      catch (...) { std::cout << "Interrupted at i = " << i << "\n"; } 
    }); 

    this_thread::sleep_for(chrono::milliseconds(800)); 
    t.interrupt(); 

    t.join(); 
    std::cout << "Interrupt requested? : " << std::boolalpha << t.interruption_requested() << "\n"; 
} 

輸出:

processed 0 
processed 1 
processed 2 
Interrupted at i = 3 
processed 3 
processed 4 
processed 5 
processed 6 
processed 7 
processed 8 
processed 9 
Interrupt requested? : false 

正如你所看到的中斷請求的行爲就像一個排序自動復位標誌。

+0

感謝您的回覆。我修改了我的代碼,並在函數B中添加了'std :: cout <<「在函數B中請求的中斷:」<< std :: bool alpha << boost :: this_thread :: interruption_requested()<<「\ n」<< endl ;'和函數'std :: cout <<「在函數B中請求的中斷:」<< std :: bool alpha << boost :: this_thread :: interruption_requested()<<「\ n」<< endl;'和我得到的輸出是'在函數B中請求中斷? :true在函數A中請求中斷? :false' – KoKa 2014-10-03 09:12:35

+0

@KoKa你去了:)回答你自己的問題:一旦'thread_interrupted'異常被拋出,「flag」被取消。 – sehe 2014-10-03 09:16:27

+0

我的情況是,如果functionB被中斷,functionA也應該被中斷,我不希望函數的代碼被執行。有什麼辦法可以執行functionA的interrupt_point嗎? – KoKa 2014-10-03 09:16:37

相關問題