一. 線程啟動
線程的啟動由傳遞一個沒有構(gòu)造函數(shù)的Callable類,之后復(fù)制到內(nèi)存,由最新的線程調(diào)用.
struct callable
{
void operator()();
};
如果該類必須不可復(fù)制,那么可以用boost::ref傳遞一個Callable對象的引用到構(gòu)造中.
boost::thread copies_are_safe()
{
callable x;
return boost::thread(x); //參數(shù)為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)); //參數(shù)為X的引用
} // x is destroyed, but the newly-created thread still has a reference
// this leads to undefined behaviour
線程可以用一個函數(shù)或callable對象為參數(shù)構(gòu)造,用boost::bind來實現(xiàn)
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);
二.線程接合與脫離
當(dāng)被銷毀時,線程稱為脫離(
detached),當(dāng)線程為脫離(detached)時,線程繼續(xù)執(zhí)行直到構(gòu)造函數(shù)中函數(shù)或callable對象執(zhí)行完畢,或程式終止.
void print();
boost::thread t(&print);
t.join();//線程銷毀
t.join();//線程已經(jīng)失效,t不指向任何線程,無作用
std::cout<<boolalpha<<t.joinable()<<std::endl;//print false statement
線程的脫離可以明確調(diào)用boost::detach()函數(shù),這種情況下線程為非現(xiàn)脫離線程(now-detached thread),變?yōu)榉蔷€程(
Not-a-Thread).
boost::thread::join() //如果線程為中斷(interrupted),引發(fā)boost::thread_interrupted異常.
boost::thread::detach() //不引發(fā)異常,如果線程不脫離,線程析構(gòu)時調(diào)用.
posted on 2009-01-22 10:01
L'雙魚 閱讀(1965)
評論(0) 編輯 收藏 引用