用boost自制线程池
初学boost,看到asio库如此好用,就做了个简单的线程池// test.cpp : 定义控制台应用程序的入口点。
//
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/detail/thread_group.hpp>
#include <boost/scoped_ptr.hpp>
#include <deque>
using namespace std;
std::deque<int> task;
boost::mutex output;//执行函数用的资源锁
//任务函数
void func(int task)//taskindex任务数据索引,用于寻找指定的任务
{
boost::mutex::scoped_lock mio(output);
cout << task << "th task run" << endl;
#include <stdlib.h>
Sleep((rand() % 10) * 100);//增大随机性,看到交叉执行的情况
cout << task << "th task end" << endl;
}
template<typename TASKTYPE>
class ThreadPool
{
public:
//用于将task里的任务分配各给threadnum个活动线程,分配时要进行线程同步
void wrapper(boost::asio::io_service* service)
{
while (true)
{
mu.lock();
if (task.empty())
{
mu.unlock();
return;
}
service->post(boost::bind(func, task.front()));
task.pop_front();
mu.unlock();
service->run();
service->reset();
}
}
ThreadPool(int _threadnum, std::deque<TASKTYPE>& _task) :threadnum(_threadnum), task(_task)
{
ppio = new boost::asio::io_service*;
if (!ppio)
throw "Error";
for (int i = 0; i < threadnum; i++)
{
ppio = new boost::asio::io_service;
if (!ppio)
throw "Error";
}
}
bool Exec()
{
try
{
//建立线程组
boost::thread_group tg;
for (int i = 0; i < threadnum; i++)
{
tg.create_thread(boost::bind(&ThreadPool::wrapper, this, ppio));
}
//等待所有任务执行完毕
tg.join_all();
}
catch (...)
{
//确保释放new
return false;
}
return true;
}
virtual ~ThreadPool()
{
for (int i = 0; i < threadnum; i++)
delete ppio;
delete[]ppio;
}
private:
int threadnum;
boost::mutex mu;//分配任务用锁
std::deque<TASKTYPE>& task;//要分配的总任务
boost::asio::io_service** ppio;//耗费的线程资源 PS:如果Io_service不是noncopyable,我也不用这么费劲用指针做,连vector都不让用
};
void main()
{
//用法示例:
int tasknum = 1000;
for (int i = 0; i < tasknum; i++)
{
task.push_back(i);//新增1000个任务
}
//使用3线程完成任务
ThreadPool<int> newtaskset(3, task);
newtaskset.Exec();
cin >> tasknum;//等待运行
}
有了这个就可以做我的dns多线程查询工具了!!!
页:
[1]