boost thread的建立方式

2021-06-06 23:39:24 字數 1642 閱讀 1710

最近在做乙個訊息中介軟體裡面涉及到多執行緒程式設計,由於跨平台的原因我採用了boost執行緒庫。在建立執行緒時遇到了幾種執行緒建立方式現總結如下:

首先看看boost::thread的建構函式吧,boost::thread有兩個建構函式:

(1)thread():構造乙個表示當前執行執行緒的執行緒物件;

(2)explicit thread(const boost::function0& threadfunc):

boost::function0可以簡單看為:乙個無返回(返回void),無引數的函式。這裡的函式也可以是類過載operator()構成的函式;該建構函式傳入的是函式物件而並非是函式指標,這樣乙個具有一般函式特性的類也能作為引數傳入,在下面有例子。

第一種方式:最簡單方法

#include

#include

void hello()

int main(int argc, char* argv)

第二種方式:複雜型別物件作為引數來建立執行緒:

#include

#include

#include

boost::mutex io_mutex;

struct count

void operator()() }

int id;

}; int main(int argc, char* argv)

第三種方式:在類內部建立執行緒;

(1)類內部靜態方法啟動執行緒

#include

#include

class helloworld

static void start()

}; int main(int argc, char* argv)

在這裡start()和hello()方法都必須是static方法。

(2)如果要求start()和hello()方法不能是靜態方法則採用下面的方法建立執行緒:

#include

#include

#include

class helloworld

void start()

}; int main(int argc, char* argv)

(3)在singleton模式內部建立執行緒:

#include

#include

#include

class helloworld

static void start()

static helloworld& getinstance()

private:

helloworld(){}

static helloworld* instance;

}; helloworld* helloworld::instance = 0;

int main(int argc, char* argv)

第四種方法:用類內部函式在類外部建立執行緒;

#include

#include

#include

#include

class helloworld

{public:

void hello(const std::string& str)

{std::cout <**:

boost thread執行緒建立方式總結

最近在做乙個訊息中介軟體裡面涉及到多執行緒程式設計,由於跨平台的原因我採用了boost執行緒庫。在建立執行緒時遇到了幾種執行緒建立方式現總結如下 首先看看boost thread的建構函式吧,boost thread有兩個建構函式 1 thread 構造乙個表示當前執行執行緒的執行緒物件 2 exp...

boost thread執行緒建立方式總結

最近在做乙個訊息中介軟體裡面涉及到多執行緒程式設計,由於跨平台的原因我採用了boost執行緒庫。在建立執行緒時遇到了幾種執行緒建立方式現總結如下 首先看看boost thread的建構函式吧,boost thread有兩個建構函式 1 thread 構造乙個表示當前執行執行緒的執行緒物件 2 exp...

Boost thread庫的使用

2009 11 26 kagula 閱讀物件 本文假設讀者有幾下skills 1 在c 中至少使用過一種多執行緒開發庫,有mutex和lock的概念。2 熟悉c 開發,在開發工具中,能夠編譯 設定boost thread庫。1 visual studio 2005 2008 with sp1 2 b...