转载地址: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