5002.boost库之thread

   最近学习 boost库,网上讲了很多的他的优势,跨平台、线程安全等 ,下面 咱们来看如何直接实现的吧。

/***************************************************************************
 * 名称:boost_thread.cpp
 * 描述:利用boost中线程库实现多线程编程.实现线程A,唤醒线程B进行计数
 * 作者:xhome
 * 时间:2019/12/27
 ****************************************************************************/
#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/lock_factories.hpp>
#include <boost/thread/condition.hpp>

using namespace std;
using namespace boost;
boost::condition_variable_any cond;  //定义条件变量.
boost::mutex  mu;

/**
 * 描述:定义线程,线程消费者,线程体函数.
 */
void thread_consumer(int arg){
    cout << "thread_consumer start ok." << endl;

    while(1){

        {  //方便资源的释放.{} 不能少,代表了锁的作用域
            auto lock = make_unique_lock(mu);
            cond.wait(lock);
            cout << "thread_consumer is wake up now --------" << endl;
        }

    }
}

/**
 * 描述:定义线程,线程消费者,线程体函数.
 */
void thread_producer(void){
    cout << "thread_producer start ok." << endl;

    while(1){
         boost::thread::sleep(boost::get_system_time() + boost::posix_time::seconds(1));  //睡眠时间1s

         cout << "thread_producer notify one +++++++++++++" << endl;
         cond.notify_one(); //通过指定的条件变量来唤醒指定的线程.
    }
}

int main(){

    //定义线程组,管理线程
    boost::thread_group  tg;
   // boost::thread  thread_1(&thread_consumer);

   //创建消费者线程.
   tg.create_thread(boost::bind(thread_consumer, 10));
   //创建生产者线程
   tg.create_thread(thread_producer);

   //线程阻塞.
   tg.join_all();

    return 0;
}

工程cmake配置 如下:

cmake_minimum_required(VERSION 3.15)
project(boost_example)

set(CMAKE_CXX_STANDARD 14)


INCLUDE_DIRECTORIES("/home/xhome/3.opt_lib/boost_1_72_x86/boost_install_x86/include")
LINK_DIRECTORIES("/home/xhome/3.opt_lib/boost_1_72_x86/boost_install_x86/lib")


add_executable(boost_example main.cpp boost_thread.cpp )
target_link_libraries(boost_example -lboost_thread -lpthread)

运行结果:

      实现了生产者将指定条件唤醒消费者

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guangshui516

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值