原文转自 http://blog.csdn.net/lee353086/article/details/4673790

本文主要由线程启动、Interruption机制、线程同步、等待线程退出、Thread Group几个部份组成。

1、线程启动。线程可以从以下四种方式启动:

(1) 用struct结构的operator成员函数启动

  1. struct callable
  2. {
  3. void operator()() { 这里略去若干行代码 }
  4. };
  5.  
  6. 这里略去若干行代码
  7.  
  8. Callable x;
  9. Boost::thread t(x);

(2) 以非成员函数形式启动线程

  1. void func(int nP)
  2. { 这里略去若干行代码
  3. }
  4. 这里略去若干行代码
  5. Boost::thread t(func,);

(3) 以成员函数形式启动线程

  1. #include <boost/bind.hpp>
  2.  
  3. class testBind
  4. {
  5. public:
  6. void testFunc(int i)
  7. {
  8. cout << i = << i << endl;
  9. }
  10. };
  11.  
  12. testBind tb;
  13. boost::thread t(boost::bind(&testBind::testFunc, &tb, ));

2、Interruption机制
可以通过thread对象的interrupt函数,通知线程,需要interrupt。线程运行到interruption point就可以退出。Interruption机制举例:

  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <boost/thread.hpp>
  4. using namespace std;
  5.  
  6. void f()
  7. {
  8. for (int i = ; i < 0x0fffffff; i++)
  9. {
  10. if (i % 0xffffff == )
  11. {
  12. cout << "i=" << ((i & 0x0f000000) >> ) << endl;
  13. cout << "boost::this_thread::interruption_requested()=" << boost::this_thread::interruption_requested() << endl;
  14. if (((i & 0x0f000000) >> ) == )
  15. {
  16. boost::this_thread::interruption_point();
  17. }
  18. }
  19. }
  20. }
  21.  
  22. int _tmain(int argc, _TCHAR* argv[])
  23. {
  24. boost::thread t(f);
  25. t.interrupt();
  26. t.join(); //等待线程结束
  27. return ;
  28. }

t.interrupt();告诉t线程,现在需要interrupt。boost::this_thread::interruption_requested()可以得到当前线程是否有一个interrupt请求。若有interrupt请求,线程在运行至interruption点时会结束。

boost::this_thread::interruption_point();就是一个interruption point。Interruption point有多种形式,较常用的有boost::this_thread::sleep(boost::posix_time::seconds(5));当没有interrupt请求时,这条语句会让当前线程sleep五秒,若有interrupt requirement线程结束。
如何使线程在运行到interruption point的时候,不会结束,可以参考下面的例子:

  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <boost/thread.hpp>
  4. using namespace std;
  5.  
  6. void f()
  7. {
  8. for (int i = ; i < 0x0fffffff; i++)
  9. {
  10. if (i % 0xffffff == )
  11. {
  12. cout << "i=" << ((i & 0x0f000000) >> ) << endl;
  13.  
  14. cout << "boost::this_thread::interruption_requested()" << boost::this_thread::interruption_requested() << endl;
  15.  
  16. if (((i & 0x0f000000) >> ) == )
  17. {
  18. boost::this_thread::disable_interruption di;
  19. {
  20. boost::this_thread::interruption_point();
  21. }
  22. }
  23. }
  24. }
  25. }
  26.  
  27. int _tmain(int argc, _TCHAR* argv[])
  28. {
  29. boost::thread t(f);
  30. t.interrupt();
  31. t.join(); //等待线程结束
  32.  
  33. return ;
  34. }

注意boost::this_thread::disable_interruption这条语句的使用,它可以使大括号内的interruption point不会中断当前线程。

3、线程同步

Boost提供了多种lock导致上手需要较长时间,还是看下面线程同步的例子比较简单,相信在多数应用中足够:
直接使用boost::mutex的例子

  1. static boost::mutex g_m;
  2. 这里略去若干行代码
  3. g_m.lock();
  4. 需要锁定的代码
  5. g_m.unlock();
  6. 这里略去若干行代码
  7. if (g_m.try_lock())
  8. {
  9. 需要锁定的代码
  10. }
  11. 这里略去若干行代码

使用lock guard的例子

  1. #include <iostream>
  2. #include <string>
  3. #include <boost/thread.hpp>
  4. #include <boost/thread/mutex.hpp>
  5. #include <boost/thread/locks.hpp>
  6.  
  7. using namespace std;
  8.  
  9. static boost::mutex g_m;
  10.  
  11. void f(string strName)
  12. {
  13. for (int i = ; i < 0x0fffffff; i++)
  14. {
  15. if (i % 0xffffff == )
  16. {
  17. boost::lock_guard<boost::mutex> lock(g_m);
  18. cout << "Name=" << strName << " i=" << ((i & 0x0f000000) >> ) << endl;
  19. }
  20. }
  21. }
  22.  
  23. int _tmain(int argc, _TCHAR* argv[])
  24. {
  25. boost::thread t(f, string("inuyasha"));
  26. boost::thread t2(f, string("kagula"));
  27. boost::thread t3(f, string("kikyou"));
  28.  
  29. {
  30. boost::lock_guard<boost::mutex> lock(g_m);
  31. cout << "thread id=" << t.get_id() << endl;
  32. }
  33.  
  34. t.join();
  35. t2.join();
  36. t3.join();
  37.  
  38. return ;
  39. }

使用unique lock的例子

  1. #include <iostream>
  2. #include <string>
  3. #include <boost/thread.hpp>
  4. #include <boost/thread/mutex.hpp>
  5. #include <boost/thread/locks.hpp>
  6.  
  7. using namespace std;
  8.  
  9. static boost::mutex g_m;
  10.  
  11. void f(string strName)
  12. {
  13. cout << "Thread name is " << strName << "-----------------begin" << endl;
  14. for (int i = ; i < 0x0fffffff; i++)
  15. {
  16. if (i % 0xffffff == )
  17. {
  18. boost::unique_lock<boost::mutex> lock(g_m);
  19.  
  20. cout << "Name=" << strName << " i=" << ((i & 0x0f000000) >> ) << endl;
  21.  
  22. lock.unlock();
  23. }
  24. }
  25. cout << "Thread name is " << strName << "-----------------end" << endl;
  26. }
  27.  
  28. int _tmain(int argc, _TCHAR* argv[])
  29. {
  30. boost::thread t(f, string("inuyasha"));
  31. boost::thread t2(f, string("kagula"));
  32. boost::thread t3(f, string("kikyou"));
  33.  
  34. t.join();
  35. t2.join();
  36. t3.join();
  37.  
  38. return ;
  39. }

同Lock_guard相比
[1]Unique lock中有owns lock成员函数,可判断,当前有没有被lock。
[2]在构造Unique Lock时可以指定boost::defer_lock_t参数推迟锁定,直到Unique Lock实例调用Lock。或采用下面的编码方式使用:
boost::unique_lock<boost::mutex> lock(mut,boost::defer_lock);
boost::unique_lock<boost::mutex> lock2(mut2,boost::defer_lock);
boost::lock(lock,lock2);
[3]它可以和Conditoin_variable配合使用。
[4]提供了try lock功能。

如果线程之间执行顺序上有依赖关系,直接到boost官网中参考条件变量(Condition variables)的使用。官网关于Conditon Variables的说明还是容易看懂的。
注意,使用一个不恰当的同步可能消耗掉1/2以上的cpu运算能力。
Thread Group

线程组使用示例,其中f函数在上面的例子已经定义

  1. int _tmain(int argc, _TCHAR* argv[])
  2. {
  3. boost::thread_group tg;
  4. tg.add_thread(new boost::thread(f,string("inuyasha")));
  5. tg.add_thread(new boost::thread(f,string("kagula")));
  6. tg.add_thread(new boost::thread(f,string("kikyou")));
  7.  
  8. tg.join_all();
  9.  
  10. return ;
  11. }

Boost::thread库的使用(转)的更多相关文章

  1. Boost::thread库的使用

    阅读对象 本文假设读者有几下Skills [1]在C++中至少使用过一种多线程开发库,有Mutex和Lock的概念. [2]熟悉C++开发,在开发工具中,能够编译.设置boost::thread库. ...

  2. boost::thread 库的使用

    转载自:http://blog.csdn.net/yockie/article/details/9181939 概要 通过实例介绍boost thread的使用方式,本文主要由线程启动.Interru ...

  3. Boost Thread学习笔记五

    多线程编程中还有一个重要的概念:Thread Local Store(TLS,线程局部存储),在boost中,TLS也被称作TSS,Thread Specific Storage.boost::thr ...

  4. Boost Thread学习笔记二

    除了thread,boost种:boost::mutexboost::try_mutexboost::timed_mutexboost::recursive_mutexboost::recursive ...

  5. Boost Thread学习笔记

    thread自然是boost::thread库的主 角,但thread类的实现总体上是比较简单的,前面已经说过,thread只是一个跨平台的线程封装库,其中按照所使用的编译选项的不同,分别决定使用 W ...

  6. boost::thread boost库线程

    一.boost::thread的创建 1.线程创建方法一: boost::shared_ptr<boost::thread> writeThread_; boost::function0& ...

  7. c++ boost asio库初学习

    前些日子研究了一个c++的一个socket库,留下范例代码给以后自己参考. 同步server: // asio_server.cpp : コンソール アプリケーションのエントリ ポイントを定義します. ...

  8. 【boost】MFC dll中使用boost thread的问题

    项目需要,在MFC dll中使用了boost thread(<boost/thread.hpp>),LoadLibraryEx的时候出现断言错误,去掉thread库引用后断言消失. 百度g ...

  9. Boost线程库学习笔记

    一.创建一个线程 创建线程 boost::thread myThread(threadFun); 需要注意的是:参数可以是函数对象或者函数指针.并且这个函数无参数,并返回void类型. 当一个thre ...

随机推荐

  1. 麦子学院python开发全套完整无加密课程

    点击了解更多Python课程>>> 麦子学院python开发全套完整无加密课程 第一阶段:Python基础准备 1.Web前端开发之HTML+CSS基础入门 2.Javascript ...

  2. Linux 系统性能

    Linux:PS命令详解与使用   要对进程进行监测和控制,首先必须要了解当前进程的情况,也就是需要查看当前进程,ps命令就是最基本进程查看命令.使用该命令可以确定有哪些进程正在运行和运行的状态.进程 ...

  3. CentOS下安装php gd库报错Error: php56w-common conflicts with php-common-5.3.3-48.el6_8.x86_64

    因为服务器缺少php gd库,因为系统是centos,就是用yum去安装,一安装就报错如下: [root@iZ28sdxghs2Z ~]# yum install php-gd Loaded plug ...

  4. JZOJ 3382. 【NOIP2013模拟】七夕祭

    3382. [NOIP2013模拟]七夕祭 Time Limits: 1000 ms  Memory Limits: 131072 KB  Detailed Limits   Goto Problem ...

  5. 对数据仓库Hive的一些认识

    首先我们得明白什么是数据仓库?   数据仓库,英文名称为Data warehouse,可简写为DW或DWH.数据仓库的目的是构建面向分析的集成化数据环境,为企业提供决策支持(Decision Supp ...

  6. python3爬虫之Urllib库(一)

    上一篇我简单说了说爬虫的原理,这一篇我们来讲讲python自带的请求库:urllib 在python2里边,用urllib库和urllib2库来实现请求的发送,但是在python3种在也不用那么麻烦了 ...

  7. 721. Accounts Merge

    https://leetcode.com/problems/accounts-merge/description/ class UnionFound { public: unordered_map&l ...

  8. oracle 事务 第二弹

    一 数据库版本 SYS@LEO1>select* from v$version; BANNER ------------------------------------------------- ...

  9. UVa 1649 Binomial coefficients 数学

    题意: \(C(n, k) = m(2 \leq m \leq 10^{15})\),给出\(m\)求所有可能的\(n\)和\(k\). 分析: 设\(minK = min(k, n - k)\),容 ...

  10. XmlSerializer 短信备份

    package com.itheima.mobileguard.utils; import java.io.File; import java.io.FileNotFoundException; im ...