最近学习 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)
运行结果:
实现了生产者将指定条件唤醒消费者