boost thread 使用笔记

 

需要用到的头文件:

//<函数类,函数绑定相关

#include 
<boost/thread/thread.hpp>

 

//<线程相关

#include 
<boost/thread/thread.hpp>

 

//<条件变量相关

#include 
<boost/thread/condition.hpp>

 

boost 线程使用:

 1//< 回调函数
 2
 3 
 4
 5void doFunc(const char* str)
 6
 7 
 8
 9{
10
11 
12
13     printf(“%s”, str);
14
15 
16
17}

18
19 
20
21 
22
23//< 初始化线程回调函数,返回值为void,参数为"hello, boost!"
24
25 
26
27boost::function<void ()> callBackFunc = boost::bind(doFunc, “hello, boost!”)
28
29 
30
31//< 创建线程,线程的同时,线程开始启动
32
33 
34
35boost::thread testThread(callBackFunc );
36
37 
38
39boost::thread::yield()   //< 放弃主线程的当前时间片,让test线程可以立刻启动
40
41 
42
43testThread.join()         //< 等待返回
44
45

 

创建线程组:

boost::thread_group grp;
grp.create_thread(callBackFunc );
grp.create_thread(callBackFunc ); 
grp.join_all( );

 

互斥访问:

boost::mutex mutex_ //定义
boost::mutext::scoped_lock lock(mutex_) //锁定互斥变量,当该变量的作用范围结束时,会自动解锁mutex_

 

条件变量:

实现线程间通信,信号量的传递。可以用来补充互斥变量不能完成的功能,比如说特定的条件下才满足的锁定。

boost::condition_variable_any writeCon; //条件变量 

writeCon.wait(
lock); //等待条件满足 

writeCon.notify_one(); 
//发送条件满足信号

 

 

只初始化一次的回调函数:

#include <iostream>
#include 
<boost/thread/thread.hpp>
#include 
<boost/thread/once.hpp>
 
// Some sort of connection class that should only be initialized once
struct Conn {
   
static void init( ) {++i_;}
   
static boost::once_flag init_;
   
static int i_;
   
// 
}
;
 
int Conn::i_ = 0;
boost::once_flag Conn::init_ 
= BOOST_ONCE_INIT;
 
void worker( ) {
   boost::call_once(Conn::init, Conn::init_);
   
// Do the real work
}

 
Conn c; 
// You probably don't want to use a global, so see the
         
// next Recipe
 
int main( ) {
 
   boost::thread_group grp;
 
   
for (int i = 0; i < 100++i)
      grp.create_thread(worker);
 
   grp.join_all( );
 
   std::cout 
<< c.i_ << '\n'// c.i_ = 1
}


//使用前,必须先定义boost::once_flag,不能为临时变量

//代码来自《C++ cookbook》


参考文章:http://www.cppblog.com/shaker/archive/2007/10/06/33583.html

posted on 2012-02-19 22:48 帅哥帅 阅读(1386) 评论(0)  编辑 收藏 引用 所属分类: boost


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜