最近需要用到Boost库的Thread库,编写点多线程的程序,Boost库是C++标准库的后援军,里面有好多已经封装好的类,例如对字符串处理的模式串,有些类是可以直接拿来使用的,有些是需要编译好作为动态库来使用的,thread库就必须提前编译好,Boost库里面大量用了c++的模板,所以基本是类都是在hpp文件里定义时就是实现的。
下面是thread类的定义。
thread 里面有个很好用的函数是bind函数,可以将函数和参数绑定到一起作为线程执行的函数,因为线程执行的函数默认是无参返回值是void的函数,这个函数可以很方便的为函数传递参数,比linux下的posix 库的thread还好用,至于他跨不夸平台跟我没有太大的关系,因为C++默认是没有线程库的,估计下次会把这个库纳入标准库中吧。
举一个thread库的例子,最近还看了点高大上的单例模式,表示第一次接触。
#include <boost/thread/thread.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello()
{
std::cout<<"Hello world, I'm a thread!"<<std::endl;
}
static void start()
{
boost::thread thrd(boost::bind(&HelloWorld::hello, &HelloWorld::getInstance()));
thrd.join();
}
static HelloWorld& getInstance()
{
if(!instance)
instance = new HelloWorld;
return *instance;
}
private:
HelloWorld() {}
static HelloWorld* instance;
};
HelloWorld* HelloWorld::instance = 0;
int main()
{
HelloWorld::start();
system("pause");
return 0;
}