初次使用boost 库


最近需要用到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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值