C++ boost thread库用法详细讲解

   2023-02-09 学习力0
核心提示:目录一、说明二、boost::thread的几个函数三、 构造一、说明boost::thread的六种使用方法总结,本文初步介绍线程的函数、构造、执行的详细解释。二、boost::thread的几个函数函数功能join()让主进程等待子线程执行完毕后再继续执行get_id()获得线程的 id 号de

一、说明

boost::thread的六种使用方法总结,本文初步介绍线程的函数、构造、执行的详细解释。

二、boost::thread的几个函数

函数 功能
join() 让主进程等待子线程执行完毕后再继续执行
get_id() 获得线程的 id 号
detach() 标线程就成为了守护线程,驻留后台运行
bool joinable() 是否已经启动,为 join()

thread::join()是个简单暴力的方法,主线程等待子进程期间什么都不能做,一般情形是主线程创建thread object后做自己的工作而不是简单停留在join上。

thread::join()还会清理子线程相关的内存空间,此后thread object将不再和这个子线程相关了,即thread object不再joinable了,所以join对于一个子线程来说只可以被调用一次,为了实现更精细的线程等待机制,可以使用条件变量等机制。

1、可会合(joinable):这种关系下,主线程需要明确执行等待操作,在子线程结束后,主线程的等待操作执行完毕,子线程和主线程会合,这时主线程继续执行等待操作之后的下一步操作。主线程必须会合可会合的子线程。在主线程的线程函数内部调用子线程对象的wait函数实现,即使子线程能够在主线程之前执行完毕,进入终止态,也必须执行会合操作,否则,系统永远不会主动销毁线程,分配给该线程的系统资源也永远不会释放。

2、相分离(detached):表示子线程无需和主线程会合,也就是相分离的,这种情况下,子线程一旦进入终止状态,这种方式常用在线程数较多的情况下,有时让主线程逐个等待子线程结束,或者让主线程安排每个子线程结束的等待顺序,是很困难或不可能的,所以在并发子线程较多的情况下,这种方式也会经常使用。

三、 构造

boost::thread有两个构造函数:

(1)thread():构造一个表示当前执行线程的线程对象;

(2)explicit thread(const boost::function0<void>& threadfunc):

boost::function0<void>可以简单看为:一个无返回(返回void),无参数的函数。这里的函数也可以是类重载operator()构成的函数;该构造函数传入的是函数对象而并非是函数指针,这样一个具有一般函数特性的类也能作为参数传入,在下面有例子。

#include <boost/thread/thread.hpp> 
#include <iostream> 
void hello() 
{ 
        std::cout << 
        "Hello world, I''m a thread!" 
        << std::endl; 
} 
int main(int argc, char* argv[]) 
{ 
        boost::thread thrd(&hello); 
        thrd.join(); 
        return 0; 
}

执行结果:

C++ boost thread库用法详细讲解

第二种情况:类重载operator()构成的函数创建线程

#include <boost/thread/thread.hpp> 
#include <boost/thread/mutex.hpp> 
#include <iostream> 
boost::mutex io_mutex; 
struct count 
{ 
        count(int id) : id(id) { } 
        void operator()() 
        { 
                for (int i = 0; i < 10; ++i) 
                { 
                        boost::mutex::scoped_lock 
                        lock(io_mutex); 
                        std::cout << id << ": " 
                        << i << std::endl; 
                } 
        } 
        int id; 
}; 
int main(int argc, char* argv[]) 
{ 
        boost::thread thrd1(count(1)); 
        boost::thread thrd2(count(2)); 
        thrd1.join(); 
        thrd2.join(); 
        return 0; 
} 

运算结果:

C++ boost thread库用法详细讲解

第三种情况:在类内部对static函数创建线程

#include <boost/thread/thread.hpp>
#include <iostream> 
class HelloWorld
{
public:
 static void hello()
 {
      std::cout <<
      "Hello world, I''m a thread!"
      << std::endl;
 }
 static void start()
 {
  boost::thread thrd( hello );
  thrd.join();
 }
}; 
int main(int argc, char* argv[])
{
 HelloWorld::start();
 return 0;
} 

注意:在这里start()和hello()方法都必须是static方法。因为static方法要比main方法提前加载,所以static方法不能调用一般方法,进一步说,static方法无法调用比它晚加载的方法,切记。 调用时用HelloWorld::start(),说明start在定义类的时候就已经ready,无需在实例化后再调用。

第四种情况:使用boost::bind函数创建线程

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream> 
#include <boost/function.hpp>
class HelloWorld
{
public:
    void hello()
    {
        std::cout <<
            "Hello world, I''m a thread!"
            << std::endl;
    }
    void start()
    {
        boost::function0< void> f = boost::bind(&HelloWorld::hello, this);
        //或boost::function<void()> f = boost::bind(&HelloWorld::hello,this);
        boost::thread thrd(f);
        thrd.join();
    }
};
int main(int argc, char* argv[])
{
    HelloWorld hello;
    hello.start();
    return 0;
}

1)定义函数指针 boost::function0< void> f

2)该指针与HelloWorld::hello函数绑定, boost::bind(&HelloWorld::hello, this);

3)线程与函数指针绑定 boost::thread thrd(f);

4)按照常规,将对象实例化后,调用类函数。

运算结果:

C++ boost thread库用法详细讲解

第五种情况:在Singleton模式内部创建线程

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream> 
class HelloWorld
{
public:
 void hello()
 {
    std::cout <<
    "Hello world, I''m a thread!"
    << std::endl;
 }
 static void start()
 {
  boost::thread thrd( boost::bind  
                   (&HelloWorld::hello,&HelloWorld::getInstance() ) ) ;
  thrd.join();
 }
 static HelloWorld& getInstance()
 {
  if ( !instance )
      instance = new HelloWorld;
  return *instance;
 }
private: 
 HelloWorld(){}
 static HelloWorld* instance;
}; 
HelloWorld* HelloWorld::instance = 0; 
int main(int argc, char* argv[])
{
 HelloWorld::start();
 return 0;
} 

此例将类对象实例化放在类内部函数中,因此无需显式实例化,就可以调用类内函数。值得研究消化。

第六种情况:在类外用类内部函数创建线程

#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <string>
#include <iostream> 
class HelloWorld
{
public:
 void hello(const std::string& str)
 {
        std::cout <<str<< std::endl;
 }
}; 
int main(int argc, char* argv[])
{ 
 HelloWorld obj;
 boost::thread thrd( boost::bind(&HelloWorld::hello,&obj,"Hello 
                               world, I''m a thread!" ) ) ;
 thrd.join();
 return 0;
} 

线程如何带参数定义?本例就是参考方法!

C++ boost thread库用法详细讲解

原文地址:https://yamagota.blog.csdn.net/article/details/127892727
 
标签: C++ Boost Thread
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Aurelius vs mORMot vs EntityDAC Delphi 的
    Aurelius vs mORMot vs EntityDAC   Delphi 的 ORM框架:http://www.tmssoftware.com/site/aurelius.asp#product-buy-onlinehttps://synopse.info/fossil/wiki/Synopse+OpenSourcehttps://www.devart.com/entitydac/download.htmlkbmMW  http://www.compo
    02-09
  • 【Ruby】Mac gem的一些坑
    前言自上一次升级MacOS系统后出现jekyll无法构建的问题,当时处理半天。谁知道最近又升级了MacOS,荒废博客多时,今天吝啬写了一篇准备发布,构建报错,问题重新。还是记录下,以防下次升级出问题。问题描述安装jekyll静态博客需要在Ruby环境下运行,于是参照
    02-09
  • iOS oc 调用 swift
    如股票oc要调用swift里面的代码 需要包含固定这个头文件项目名称 LiqunSwiftDemo-Swift.h         #ProjectName#-Swift.h固定的写法swift 目的 是取代oc 但是 不会完全取代 只是前端的替换LiqunSwiftDemo-Swift 点进去 可以看到 所有的swift代码 都产生
    02-09
  • objective-c NSTimer 定时器
    -(void)initTimer{//时间间隔NSTimeInterval timeInterval =3.0 ;//定时器repeats 表示是否需要重复,NO为只重复一次NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(mobileAnimation) userInfo:nil
    02-09
  • Objective-C  日记③ 字符串
    Objective-C 日记③ 字符串
    一、创建字符串、类方法   公式创建NSString  +(id) stringWithFormat:(NSString *) format,……;eg:  NSString *height;  height=[NSString stringWithFormat:@"高度是: %d 长度: %d",10,20];得到的字符串:“高度是: 10 长度: 20” 注意:  省
    02-09
  • Objective-C KVC机制
    Objective-C KVC机制http://blog.csdn.net/omegayy/article/details/7381301全部推翻重写一个版本,这是我在公司内做技术分享的文档总结,对结构、条理做了更清晰的调整。 1.    基本概念MODEL主要是英文文档里面经常出现的一些概念,讲解一下,方便英文
    02-09
  • objective-c 加号 减号 - +
    “加号代表static”是错误的说法,可能跟你那样表达的人其实意思是:“前置加号的方法相当于Java 里面的静态方法”。在Oc中,方法分为类方法和实例方法。前置加号(+)的方法为类方法,这类方法是可以直接用类名来调用的,它的作用主要是创建一个实例。有人把
    02-09
  • Objective-C  日记①
    Objective-C 日记①
    1、Xcode的.m扩展名表示文件含有Object-C代码,C以.c文件,C++以.cpp文件2、头文件声明:C使用:#include,O-C使用#import(当然你也可以使用#include) 3、输出方式:  C:printf("",参数);  O-C:NSLog(@"",参数); 4、布尔类型  C:bool 具有true
    02-09
  • ASP.NET MVC 操作AD 获取域服务器当前用户姓
    #region 根据当前登录域账号 获取AD用户姓名和所在OU目录/// summary/// 根据当前登录域账号 获取AD用户姓名和所在OU目录/// /summary/// param name="searchUser"要搜索的当前用户名/param/// param name="paths"out返回该用户所在OU目录/param/// param nam
    02-09
  • swift和OC - 拆分数组 和 拆分字符串
    1. 拆分数组 /// 根据 数组 截取 指定个数返回 多个数组的集合func splitArray( array: [Date], withSubSize subSize: Int) - [[Date]] {//数组将被拆分成指定长度数组的个数let count = array.count% subSize == 0 ? (array.count/ subSize) : (array.count
    02-08
点击排行