centos7 boost学习1 使用boost::asio实现简易线程池 -lboost_system

11 篇文章 0 订阅
10 篇文章 0 订阅

转载地址:https://segmentfault.com/a/1190000010674396

threadpool.h

#include <stdio.h>
#include <string.h>
#include <iostream>
//#include <boost/thread/thread_pool.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <thread>

using namespace std;
 using namespace boost;
 typedef std::shared_ptr<std::thread> thread_ptr;
 typedef std::vector<thread_ptr> vecThread;
 
 class ThreadPool {
 public:
     ThreadPool(int num) : threadNum_(num), stopped_(false), work_(io_) {
         for(int i=0; i<threadNum_; ++i) {
             threads_.push_back(std::make_shared<std::thread>([&](){io_.run();}));
         }
     }   
     ~ThreadPool() {
         stop();  
     }   
     template<typename F, typename...Args>
     void post(F &&f, Args&&...args) {
         io_.post(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
     }   
     void stop() {
         if(!stopped_) {
             io_.stop();    
             for(auto t : threads_) t->join();
             stopped_ = true;
         }
     }   
 
 private:
     bool             stopped_;
     vecThread        threads_;
     int              threadNum_;
     asio::io_service io_;
     asio::io_service::work work_;
 };

 

main.cpp

#include <chrono>
#include "threadpool.h" 

void test1(int x) {std::cout<<"test 1:"<<x<<std::endl;}
 void test2(int y) {std::cout<<"test 2:"<<y<<std::endl;}
 
#define _GLIBCXX_USE_NANOSLEEP 1

 int main()
 {
     ThreadPool threads(5);
     threads.post([](){std::cout<<"test 1"<<std::endl;});
     threads.post([](){std::cout<<"test 2"<<std::endl;});
     threads.post(test1, 3); 
     threads.post(test2, 5); 
 
     std::this_thread::sleep_for(std::chrono::seconds(3));
     threads.stop();
 }

 

 

 

gcc编译

g++ -g -Wall -std=gnu++0x threadpool.h main.cpp -o main -lboost_system

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

金士顿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值