您的位置:首页 > 其它

使用boost::thread跨平台多线程 (一) 基本使用

2007-09-12 00:35 363 查看

使用boost::thread跨平台多线程 (一) 基本使用

作者: 江淼
Blog: http://blog.csdn.net/jiangfriend
时间: 2007-9-12 00:31

关于boost::thread的概述我也不多说,一句话,boost的跨平台的多线程库,我们直接切入正题。

一、基本使用

头文件 <boost/thread/thread.hpp>
namespace boost {
class thread;
class thread_group;
}

1、thread
thread的构造形式为explicit thread(const boost::function0<void>&);
如果你对boost::function不熟,那么我听我简短的介绍一下:
boost::function0<void>可以简单看为:一个无返回(返回void),无参数的函数。
这里的函数也可以是类重载operator()构成的函数。

举例来说如下形都可以转化为function0<void>。
void run(void)
{
}

struct Run
{
void operator()(void) {}
};

只要带参数构造一个thread实例那么就是构建了一个线程,相当的方便快捷。
于是有了我们第一个例子:
例一:

#include <boost/thread.hpp>
#include <iostream>

struct Run
{
void operator()(void)
{

std::cout<<__FUNCTION__<<std::endl;
}
};
void run(void)
{
std::cout<<__FUNCTION__<<std::endl;
}

int main(int argc, char* argv[])
{
Run r;
boost::thread thrd(r);
boost::thread thrdb(run);
return 0;
}

运行后发生了什么?线程起动了,但一闪而过,结果都没能输出全就运行结束了。那该怎么办呢?
答:使用thread::join,当join后的thread在该线程未执行结束会一直处于阻塞状态。

改下例子中主程序main为
{
Run r;
boost::thread thrd(r);
boost::thread thrdb(run);
thrd.join();
thrdb.join();
return 0;
}
看到结果了,但似乎线程有点不同步,呃。。暂时放在一旁吧。
什么?你觉得void(void)的函数连变量入口都没,传值不方便?其实你错了,当你用会了boost::bind,会发现函数有多少参数都不是问题,都可以轻松bind为void(void)形式。我几乎可以说boost::thread最基本的的使用就是boost::thread+boost::function+boost::bind的结合。

2、thread_group
大家一定注意到除了thread还有thread_group,顾名思义,thread_group就是thread的group,看看main主程序有点烦琐,引入thread_group看看效果
先认识下thread_group的成员函数:

thread* create_thread(const boost::function0<void>&); //创建一个线程
void add_thread(thread*); //加入一个已存在的线程
void remove_thread(thread*); //移除一个线程
void join_all(); //全部等待结束

很清晰,改造开始
{
Run r;
boost::thread_group grp;
grp.create_thread(r); //使用create_thread
grp.add_thread(new boost::thread(run)); //使用add_thread
grp.join_all();
return 0;
}
运行,结果完全一样。

注意:当thread_group析构时会自动delete已加入的thread

{
boost::thread_group grp;
boost::thread* thrd=grp.create_thread(r);
grp.join_all();
delete thrd;
} //错误, grp在析构时对已删除的thrd再进行删除

若要手动管理,可改为:
{
Run r;
boost::thread_group grp;
boost::thread* thrd=grp.create_thread(r);
grp.join_all();
grp.remove_thread(thrd); //把thrd移出grp
delete thrd;
return 0;
}

好了,以上就是thread的最基本的使用方法。

相关链接:

boost官方网站 http://www.boost.org
boost::thread 帮助文档 http://www.boost.org/doc/html/thread.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: