使用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.orgboost::thread 帮助文档 http://www.boost.org/doc/html/thread.html
相关文章推荐
- 使用boost::thread跨平台多线程 (二) 线程同步-互斥
- <Boost> boost::thread 多线程的使用
- Java多线程——thread及runnable的基本使用及交替执行
- BOOST 库 thread类线程使用 多线程处理的理解
- 多线程的几中创建方法与基本使用
- iOS多线程编程之NSThread的使用
- iOS多线程编程之NSThread的使用
- iOS 多线程之NSThread简单使用
- C#中的多线程使用 -- Thread 类
- iOS开发多线程-GCD的基本使用
- Android 多线程:使用Thread和Handler (从网络上获取图片)
- Android开发之多线程编程Thread和Runnable使用
- JAVA多线程实现的三种方式(继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程)
- Android开发之多线程编程Thread和Runnable使用
- Boost::Thread使用示例
- java多线程Thread与Runnable的区别与使用深入理解
- Android开发之多线程编程Thread和Runnable使用
- Java多线程(一)、多线程的基本概念和使用
- Boost.asio的简单使用(timer,thread,io_service类)
- Java多线程(一)、多线程的基本概念和使用(转)