boost线程

1包含thread头文件及使用boost命名空间
#include<boost/thread.hpp>

2.使用等待当前线程的成员函数
join()一直阻塞等待,直到当前线程结束。
time_join()等待当前线程结束或者最多等待多少时间后返回[当当前线程已经结束但等待时间还未到时也返回]

3.几种使用方法
第一种方式:最简单方法
 
 
  1. void print_string( const string &str );  
  1.  
  1. int _tmain(int argc, _TCHAR* argv[])  
  1. {        
  1.     boost::thread test1( print_string, "hello" );  
  1.    test1.join();  
  1.    return 0;
第二种方式:在类内部创建线程 1)类内部静态方法启动线程 class HelloWorld { public: static void hello() { std::cout << "Hello world, I''m a thread!"<< std::endl; } static void start() { boost::thread thrd( hello ); thrd.join(); } }; int main(int argc, char* argv[]) { HelloWorld::start();   return 0; } 在这里start()和hello()方法都必须是static方法。

(2)类内部非静态方法启动线程 将hello成员函数,改为非静态函数。
class HelloWorld
{
public:
	void hello()
	{
		std::cout << "Hello world, I''m a thread!"<< std::endl;
	}
	void start()
	{
		boost::thread thrd(boost::bind((&HelloWorld::hello,this));
		thrd.join();
	}
};
int main(int argc, char* argv[])
{
	HelloWorld hl;
       hl.start();
	return 0;
}

第三种:用类内部函数在类外部创建线程 class HelloWorld
{
public:
	void hello(const std::string& str)
	{
		std::cout << str << std::endl;
	}
};
int main(int argc, char* argv[])
{
	HelloWorld  hl;
	boost::thread thr_test(boost::bind((&HelloWorld::hello,hl,"test----"));  
    	thr_test.detach();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值