Boost线程学习简记

Boost线程学习简记

头文件

#include <boost/thread.hpp>

创建线程

boost::thread是线程类,创建线程非常简单,只需要创建一个thread对象,并把线程工作函数作为参数传给构造参数。

void output()

{

   std::cout<<"output"<<std::endl;

}

boost::thread t(output);

 

传递参数

如果我们的工作函数需要参数怎么办呢?

void output2(int v)

{

   std::cout<<"output : "<<v<<std::endl;

}

boost::thread t(output2,4);

如果我们的线程函数有多个参数,不论什么类型,都写成如下形式(只要不超过十个)

boost::thread t(fun,arg1,arg2,);

 

合并到主线程

t.join();

等待线程函数执行完毕

 

Sleep函数

boost::this_thread::sleep()

这里的sleep()函数并不是休眠多久的意思,而是睡眠到什么时候。

所以如果我们想要他休眠一秒钟,就要先计算一秒钟之后的时间是多少然后传给sleep

   //计算出sec+0.0000000001*nsec秒后的时间

boost::xtime getNextTime(int sec,int nsec)

   {

      boost::xtime t;

      boost::xtime_get(&t, boost::TIME_UTC);

      t.sec += sec;

      t.nsec += nsec;

      return t;

   }

boost::this_thread::sleep(getNextTime(1,0));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值