1.前言
標準C++線程即將到來。CUJ預言它將衍生自Boost線程庫,現在就由Bill帶領我們探索一下Boost線程庫。 就在幾年前,用多線程執行程序還是一件非比尋常的事。然而今天互聯網應用服務程序普遍使用多線程來提高與多客戶鏈接時的效率;為了達到最大的吞吐量,事務服務器在單獨的線程上運行服務程序;GUI應用程序將那些費時,復雜的處理以線程的形式單獨運行,以此來保證用戶界面能夠及時響應用戶的操作。這樣使用多線程的例子還有很多。
但是C++標準并沒有涉及到多線程,這讓程序員們開始懷疑是否可能寫出多線程的C++程序。盡管不可能寫出符合標準的多線程程序,但是程序員們還是會使用支持多線程的操作系統提供的多線程庫來寫出多線程C++程序。但是這樣做至少有兩個問題:這些庫大部分都是用C語言完成的,如果在C++程序中要使用這些庫就必須十分小心;還有,每一個操作系統都有自己的一套支持多線程的類庫。因此,這樣寫出來得代碼是沒有標準可循的,也不是到處都適用的(non-portable)。Boost線程庫就是為了解決所有這些問題而設計的。
Boost是由C++標準委員會類庫工作組成員發起,致力于為C++開發新的類庫的組織。現在它已經有近2000名成員。許多庫都可以在Boost源碼的發布版本中找到。為了使這些類庫是線程安全的(thread-safe),Boost線程庫被創建了。
許多C++專家都投身于Boost線程庫的開發中。所有接口的設計都是從0開始的,并不是C線程API的簡單封裝。許多C++特性(比如構造函數和析構函數,函數對象(function object)和模板)都被使用在其中以使接口更加靈活。現在的版本可以在POSIX,Win32和Macintosh Carbon平臺下工作。
2.常見創建線程方法
#include <boost/thread/thread.hpp>
#include <iostream>
#include <string>void hello(const char* s,int b,int c)
{std::cout << s << std::endl;std::cout << b << std::endl;std::cout << c << std::endl;
}class Base{Base(){std::cout<<"hello world!"<<std::endl;}
};
int main(int argc, char* argv[])
{boost::thread *plan = new boost::thread(boost::bind(&hello,"hello,I am thread",1000,2000));//thrd(&Base);plan->join();boost::thread *plan2 = new boost::thread(boost::bind(&hello,"hello,I am thread2",10002,20002));//thrd(&Base);plan2->join();return 0;
}
下面這句是創建線程的語句,hello是線程調用的函數,bind是傳入參數
boost::thread *plan = new boost::thread(boost::bind(&hello,"hello,I am thread",1000,2000));
運行如下命令編譯:
g++ -std=c++11 main.cpp -lpthread -lboost_system -lboost_thread -o main
執行:
./main
結果如下:
hello,I am thread
1000
2000
hello,I am thread2
10002
20002
3.在類中創建Boost::thread線程
代碼:
#include <boost/thread/thread.hpp>
#include <iostream>
#include <string>void hello(const char* s,int b,int c)
{std::cout << s << std::endl;std::cout << b << std::endl;std::cout << c << std::endl;
}class Base{
public:const char* s_;int a_;int b_;Base(){std::cout<<"hello world!"<<std::endl;}
public:void threaFUnction(){boost::thread *plan2 = new boost::thread(boost::bind(&Base::hellowold,this,s_,a_,b_));//thrd(&Base);plan2->join();}
public:void hellowold(const char* s,int a,int b){ std::cout << s << std::endl;std::cout << a << std::endl;std::cout << b << std::endl;}};/*
void Base::hellowold(const char* s,int a,int b)
{std::cout << s << std::endl;std::cout << b << std::endl;std::cout << c << std::endl;
}
*/int main(int argc, char* argv[])
{// boost::thread *plan = new boost::thread(boost::bind(&hello,"hello,I am thread",1000,2000));//thrd(&Base);//plan->join();//boost::thread *plan2 = new boost::thread(boost::bind(&hello,"hello,I am thread2",10002,20002));//thrd(&Base);// plan2->join();Base * base = new Base();base->a_ = 10;base->b_ = 12;base->s_ = "hello Thread Class!";base->threaFUnction();return 0;
}
主要是如下代碼:
void threaFUnction(){boost::thread *plan2 = new boost::thread(boost::bind(&Base::hellowold,this,s_,a_,b_));//在類中子成員創建線程plan2->join();}
執行方式和上述一樣,執行結果如下:
hello world!
hello Thread Class!
12
10
Reference
- C++ Boost Thread 編程指南