綰跨▼鐨勫惎鍔ㄧ敱浼犻掍竴涓病鏈夋瀯閫犲嚱鏁扮殑Callable綾?涔嬪悗澶嶅埗鍒板唴瀛?鐢辨渶鏂扮殑綰跨▼璋冪敤.
struct callable
{
void operator()();
};
濡傛灉璇ョ被蹇呴』涓嶅彲澶嶅埗,閭d箞鍙互鐢╞oost::ref浼犻掍竴涓狢allable瀵硅薄鐨勫紩鐢ㄥ埌鏋勯犱腑.
boost::thread copies_are_safe()
{
callable x;
return boost::thread(x); //鍙傛暟涓篨鐨勪竴浠芥嫹璐?/span>
} // 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)); //鍙傛暟涓篨鐨勫紩鐢?/span>
} // x is destroyed, but the newly-created thread still has a reference
// this leads to undefined behaviour
綰跨▼鍙互鐢ㄤ竴涓嚱鏁版垨callable瀵硅薄涓哄弬鏁版瀯閫?鐢╞oost::bind鏉ュ疄鐜?br>
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);
浜?綰跨▼鎺ュ悎涓庤劚紱?br>褰撹閿姣佹椂,綰跨▼縐頒負鑴辯(detached),褰撶嚎紼嬩負鑴辯(detached)鏃?綰跨▼緇х畫鎵ц鐩村埌鏋勯犲嚱鏁頒腑鍑芥暟鎴朿allable瀵硅薄鎵ц瀹屾瘯,鎴栫▼寮忕粓姝?
void print();
boost::thread t(&print);
t.join();//綰跨▼閿姣?/em>
t.join();//綰跨▼宸茬粡澶辨晥,t涓嶆寚鍚戜換浣曠嚎紼?鏃犱綔鐢?/em>
std::cout<<boolalpha<<t.joinable()<<std::endl;//print false statement
綰跨▼鐨勮劚紱誨彲浠ユ槑紜皟鐢╞oost::detach()鍑芥暟,榪欑鎯呭喌涓嬬嚎紼嬩負闈炵幇鑴辯綰跨▼(now-detached thread),鍙樹負闈炵嚎紼?Not-a-Thread).
boost::thread::join() //濡傛灉綰跨▼涓轟腑鏂?interrupted),寮曞彂boost::thread_interrupted寮傚父.
boost::thread::detach() //涓嶅紩鍙戝紓甯?濡傛灉綰跨▼涓嶈劚紱?綰跨▼鏋愭瀯鏃惰皟鐢?

]]>