在上篇博文中,我们简单地将每个线程的 执行函数进行了抽象化,这篇博文在此基础上设计了一个简单的任务池,废话不说,直接上代码:
#ifndef __TASK__POOL__H
#define __TASK__POOL__H
#include "Thread.h"
#include "Task.h"
#include <stack>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
static boost::mutex g_mutex;
class TaskPool
{
public:
TaskPool(){}
~TaskPool(){}
public:
void addTask(Task* task)
{
g_mutex.lock();
taskList.push(task);
g_mutex.unlock();
}
void runTask()
{
Thread* thread = threadPool.assignThread();
assert(thread);
g_mutex.lock();
Task* task = taskList.top();
taskList.pop();
g_mutex.unlock();
thread->setThreadFun(task);
thread->run();
}
private:
std::stack<Task*> taskList;
ThreadPool threadPool;
};
#endif
其他的代码请参见上篇博文,这里面我只是实现了两个函数,其实完全可以根据需要在此自行添加,另外在taskpool中使用了boost::mutex这个互斥量,主要是为了简单,其次如果可以的话,完全可以换成其他的几种同步机制,如果有机会的话,我们会对其他的几种机制进行分析介绍的,在此不再多说,接下来看看测试用例吧,代码如下:
#include "Thread.h"
#include "Task.h"
#include "TaskPool.h"
int main()
{
PrintTask printTask;
CacluateTask cacluateTask;
CommTask commTask;
/* int threadNum = 10;
ThreadPool threadPool(10);
threadPool.addThread(threadNum,&printTask);
threadPool.startAll();
threadPool.stopAll();
sleep(1);
Thread* thread = threadPool.assignThread();
assert(thread);
thread->setThreadFun(&cacluateTask);
thread->run();
sleep(1);
thread = threadPool.assignThread();
assert(thread);
thread->setThreadFun(&commTask);
thread->run();
sleep(5);
threadPool.delThread(threadNum);
*/
TaskPool taskPool;
taskPool.addTask(&printTask);
taskPool.addTask(&cacluateTask);
taskPool.addTask(&commTask);
taskPool.runTask();
//taskPool.runTask();
return 0;
}
总结
上述代码很简单,只是对Task进行了简单的管理,但是思想也是值得学习的,里面只涉及了一个线程库,如果需要的话,完全可以在此基础上进行扩展出更为复杂的功能,写这篇博文的主要目的就是为了能够将线程池应用到任务当中,这也是任务池的设计思想,有机会的话,自己会对这块进行深化,希望能够有所收获。
如果需要,请注明转载,多谢