一. 線程啟動
線程的啟動由傳遞一個沒有構造函數的Callable類,之后復制到內存,由最新的線程調用.
struct callable
{
void operator()();
};
如果該類必須不可復制,那么可以用boost::ref傳遞一個Callable對象的引用到構造中.
boost::thread copies_are_safe()
{
callable x;
return boost::thread(x); //參數為X的一份拷貝
} // x is destroyed, but the newly-created thread has a copy, so this is OK
boost::thread oops()
{
callable x;
return boost::thread(boost::ref(x)); //參數為X的引用
} // x is destroyed, but the newly-created thread still has a reference
// this leads to undefined behaviour
線程可以用一個函數或callable對象為參數構造,用boost::bind來實現
void find_the_question(int the_answer);
boost::thread deep_thought_2(boost::bind(find_the_question,42));
void print();
boost::thread t=boost::thread(&print);
二.線程接合與脫離
當被銷毀時,線程稱為脫離(
detached),當線程為脫離(detached)時,線程繼續執行直到構造函數中函數或callable對象執行完畢,或程式終止.
void print();
boost::thread t(&print);
t.join();//線程銷毀
t.join();//線程已經失效,t不指向任何線程,無作用
std::cout<<boolalpha<<t.joinable()<<std::endl;//print false statement
線程的脫離可以明確調用boost::detach()函數,這種情況下線程為非現脫離線程(now-detached thread),變為非線程(
Not-a-Thread).
boost::thread::join() //如果線程為中斷(interrupted),引發boost::thread_interrupted異常.
boost::thread::detach() //不引發異常,如果線程不脫離,線程析構時調用.
posted on 2009-01-22 10:01
L'雙魚 閱讀(1965)
評論(0) 編輯 收藏 引用