boost库的thread_pool学习

一、 boost库版本

Version 1.69.0

二、boost库安装

  1. 下载源码 boost_1_69_0.tar.bz2
  2. 解压安装:  ./bootstrap.sh;  ./b2 install

三、牛刀小试

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <thread>
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/post.hpp>
#include <boost/bind.hpp>
#include <boost/thread/pthread/thread_data.hpp>
using namespace std;
 
 
void task_1()
{
	cout << "ttask_1 start: " <<std::this_thread::get_id() << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << "hello task_1" << endl;
		sleep(1);
	}
}
 
void task_2()
{
	sleep(2);
	cout << "task_2 start:" << std::this_thread::get_id()<<endl;
	for (int i = 0; i < 5; i++)
	{
		cout << "hello task_2" << endl;
		sleep(1);
	}
}
 
void task_addParam(int a)
{
	sleep(2);
	cout << "task_3 start:" << std::this_thread::get_id()<<endl;
	for (int i = 0; i < 5; i++)
	{
		cout <<"a + "<<i<<": "<<a + i << endl;
		sleep(1);
	}
}
 
 
int main()
{

	boost::asio::thread_pool tp(3);
	boost::asio::post(tp, task_1);
	boost::asio::post(tp, task_2);
	boost::asio::post(tp, boost::bind(task_addParam, 3));
    tp.join();
	return 0;
}

编译: 

g++ -lboost_thread -o main thread_pool.cpp -I/usr/local/include -lpthread -std=c++11

输出:

ttask_1 start: 139705846953728
hello task_1
hello task_1
task_3 start:139705838561024
a + 0: 3
task_2 start:139705855346432
hello task_2
hello task_1
a + 1: 4
hello task_2
hello task_1
a + 2: 5
hello task_2
hello task_1
hello task_2
a + 3: 6
hello task_1
a + 4hello task_2: 7

hello task_1
hello task_1
hello task_1
hello task_1

 

这个错误是因为在Boost.Asio中没有找到`thread_pool`类的成员。`thread_pool`类在较新的Boost版本中是不再提供的。 如果你想使用线程池功能,可以考虑使用Boost.Asio中提供的其他替代方案。例如,你可以使用`io_context`和`executor_work_guard`来实现线程池的功能。下面是一个简单的示例代码: ```cpp #include <boost/asio.hpp> #include <iostream> class ThreadPool { public: ThreadPool(size_t numThreads) : work_(ioContext_) { for (size_t i = 0; i < numThreads; ++i) { threads_.emplace_back([this]() { ioContext_.run(); }); } } ~ThreadPool() { ioContext_.stop(); for (auto& thread : threads_) { thread.join(); } } template <typename Task> void post(Task&& task) { boost::asio::post(ioContext_, std::forward<Task>(task)); } private: boost::asio::io_context ioContext_; boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_; std::vector<std::thread> threads_; }; int main() { ThreadPool threadPool(4); for (int i = 0; i < 10; ++i) { threadPool.post([i]() { std::cout << "Task " << i << " executed in thread " << std::this_thread::get_id() << std::endl; }); } std::this_thread::sleep_for(std::chrono::seconds(2)); return 0; } ``` 在这个示例中,我们使用了`io_context`和`executor_work_guard`来创建了一个简单的线程池。`post`方法用于将任务提交到线程池中执行。 请确保在编译时链接了Boost.Asio,并将头文件路径正确地包含在编译器的搜索路径中。希望这能帮助你解决问题。如有更多疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值