boost线程库学习--(2)创建带线程的类并测试

来源:互联网 发布:淘宝购买人数太多 编辑:程序博客网 时间:2024/06/14 23:25

本例子将创建一个带有线程的类,并测试。程序功能如下:程序启动后创建一个带有线程的对象,该对象每隔一秒打印一个helloworld,该对象的线程与主线程同时运行,主线程每隔yimiao打印一个main。测试环境为ubuntu12.04,使用boost1_55的库,程序源代码如下:

1、程序源代码

/* *File:test.cpp *Author:yingxianFei *Date:2014-2-19 *Description:linux下的boost线程库测试程序,程序中有一个Helloworld对象,对象主中封装了一个每隔一秒打印一个hello,world的线程\    主线程每隔一秒打印一个main */#include <boost/thread/thread.hpp>#include <boost/function/function0.hpp>#include <boost/bind.hpp>#include <iostream>#include <unistd.h>using namespace boost;using namespace std;/* *Class :Helloworld *Description:用于测试对象中使用线程的类 */class Helloworld{    public:Helloworld();virtual ~Helloworld();void start(void);protected:void hello(void);};/* *Function:Helloworld *Description:构造函数,用于创建一个带线程成员函数的对象 *Input:none *Return:对象实例 */Helloworld::Helloworld(){   cout<<"Create hello,world object..."<<endl;}/* * *Function:~Helloworld *Description:析构函数 *Input:none *Return:none */Helloworld::~Helloworld(){   cout<<"Delete hello,world object..."<<endl;}/* *Function:start *Description:绑定要执行的任务并开始执行 *Input:none *Return:none */void Helloworld::start(){  boost::function0<void> f = boost::bind(&Helloworld::hello,this);  boost::thread th(f); // th.join();//阻塞主线程,等待该线程结束才开始执行主线程  th.detach();//分派任务,让子线程与主线程同时运行}/* *Function:hello *Description:打印函数,每隔一秒打印一个hello,world *Input:none *Out:none */void Helloworld::hello(){while(1)  {       cout<<"Hello,world"<<endl;   sleep(1);}}/* *Function:main *Description:主函数,创建测试对象并启动,同时每隔一秒打印一个main *Input:none *Return:none */int main(void){Helloworld obj;obj.start();while(1)  {   cout<<"main"<<endl;   sleep(1);}return 0;}

2、makefile文件内容如下,-I  用于指定我的boost库的include文件路径,-L 用于指定我的boost库的lib文件路径。

CC = g++CFLAG += -WallCINCLUDE = -I/usr/local/boost/x86/includeCLIB = -L/usr/local/boost/x86/libCLD = -lboost_system -lboost_threadSRCS := \test.cppTARGET:=testall:$(TARGET)$(TARGET):$(SRCS)$(CC) $(CFLAG) $(CINCLUDE) $(CLIB) $(CLD) $^ -o $@.PHONY:cleanclean:-@rm $(TARGET)

3、编译并执行测试程序。

make,之后生成test可执行文件,直接执行即可。

0 0
原创粉丝点击