boost的多线程学习一

来源:互联网 发布:单片机圆孔插座 编辑:程序博客网 时间:2024/05/22 12:36

http://www.cppblog.com/AthrunOnline/articles/82413.html


一、基本使用
头文件 <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>。

1  void  run( void )
2  {
3 } 

4  
5  struct  Run
6  {
7       void   operator ()( void  {} 
8 } 
;
9 

 

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

 1  #include  < boost / thread.hpp > 
 2 #include  < iostream > 
 3  
 4  struct  Run
 5       {
 6      void   operator ()( void )
 7           {
 8     
 9         std::cout << __FUNCTION__ << std::endl;
10         } 

11     } 
;
12  void  run( void )
13       {
14     std::cout << __FUNCTION__ << std::endl;
15     } 

16  
17  int  main( int  argc,  char *  argv[])
18       {
19     Run r;
20     boost::thread thrd(r);
21     boost::thread thrdb(run);
22      return   0 ;
23     } 

24  
25 

 

运行后发生了什么?线程起动了,但一闪而过,结果都没能输出全就运行结束了。

那该怎么办呢?
答:使用thread::join,当join后的thread在该线程未执行结束会一直处于阻塞状态。

改下例子中主程序main为

1       {
2     Run r;
3     boost::thread thrd(r);
4     boost::thread thrdb(run);
5     thrd.join();
6     thrdb.join();
7      return   0 ;
8     }


看到结果了,但似乎线程有点不同步,呃。。暂时放在一旁吧。
什么?你觉得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的成员函数:

 

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

 

很清晰,改造开始

1       {
2     Run r;
3     boost::thread_group grp;
4     grp.create_thread(r);  // 使用create_thread 
5      grp.add_thread( new  boost::thread(run));  // 使用add_thread 
6      grp.join_all();
7      return   0 ;
8     }


运行,结果完全一样。

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

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

 

若要手动管理,可改为:

1       {
2     Run r;
3     boost::thread_group grp;
4     boost::thread *  thrd = grp.create_thread(r);
5     grp.join_all();
6     grp.remove_thread(thrd);  // 把thrd移出grp 
7      delete thrd;
8      return   0 ;
9     }

 

好了,


0 0