(十)boost庫之多執行緒

2021-09-08 18:24:04 字數 1759 閱讀 1698

使用boost庫可以方便的建立乙個執行緒,並提供最多支援9個引數的執行緒函式,相對於void*來說,方便了很多,建立執行緒主要提供了一下3種方式:

執行緒庫標頭檔案:#include

a、使用全域性函式作為執行緒執行體

voidfunc(intncount) 

}
int _tmain(int argc, _tchar* ar**)

b、使用成員函式作為執行緒執行體

class a

}
};
//執行緒引數都採用值傳遞,因此即使如下傳入乙個臨時變數作為引數,執行緒照樣可以正確執行

//如果需要傳遞引用,可通過ref庫來實現

boost::thread *pth;
voidtestthread()

c、仿函式作為執行緒執行體

classb

void operator()()

}
int nmem;

};
//執行緒thread物件銷毀時,會與執行緒執行體分離,執行緒執行體不受影響

voidtestthread2()

結合以上方法,我們可以輕而易舉的就建立乙個執行緒,結合boost.bind庫和lambda表示式,將會更方便。如:

boost::thread th3((intncount)
}, 10);
執行緒不是在任意時刻都可以被中斷,因此要實現中斷,需要我們自己決定什麼時候可以被中斷,boost庫定義了以下函式是可以被中斷的:

成員函式interrupt,執行正在執行的執行緒中斷,被中斷的執行緒會丟擲異常類boost::thread_interrupted,程式應該自行處理該異常,以確保執行緒正確結束。

voidinterrupt_thread(intncount) 

}
catch(boost::thread_interrupted&)

}
boost::thread th2(interrupt_thread, 100);

boost::this_thread::sleep(boost::posix_time::seconds(4));

th2.interrupt();
在以上中斷函式中,除了最後乙個,其它都是等待函式,如果想在非等待情況下,執行執行緒被中斷,就可以使用最後乙個函式。

比如我們可以將上面的boost::this_thread::sleep(boost::posix_time::seconds(1));替換成  boost::this_thread::interruption_point();

有時我們需要管理一組執行緒物件,進行統一的等待處理,使用boost::thread_group可以輕鬆的處理。

#include 

voidthreadgroup()

Boost之多執行緒

c 標準庫沒有涉及執行緒,在c 中,雖然不可能寫出標準相容的多執行緒程式,程式設計師可以使用特定作業系統提供的執行緒庫來寫出多執行緒程式來。可是,這至 少導致兩個突出的問題 作業系統普遍提供的是c庫,在c 中使用要更小心,每個作業系統都有自己的一套支援多執行緒的庫 另外,不標準,不可移植。boost...

boost庫 多執行緒

1.執行緒管理 最重要的乙個類是boost thread,是在boost thread.hpp裡定義的,用來建立乙個新執行緒。include include void wait int seconds void thread int main 乙個特定的執行緒可以通過thread變數訪問,通過這個變...

boost多執行緒

linux下編譯多執行緒程式 g o 1.out 1.cpp i boost include l boost lib lboost thread 建立執行緒 標頭檔案 namespace boost thread 構造乙個表示當前執行執行緒的執行緒物件 explicit thread const b...