在上篇博文中,我们自己设计实现了一个简单的多线程池,功能实现很简单,里面有很多的不足,例如对于线程的回调函数,只是在以普通的函数来实现,在此我们想借以任务的形式来给线程池线程指定相应的任务,因而来实现一个任务池+线程池的设计理念,下面我们就开始设计我们的任务,代码如下:
#ifndef __TASK__H
#define __TASK__H
#include <stdio.h>
#include <stdlib.h>
class Task
{
public:
Task(){}
virtual ~Task(){}
public:
virtual void doWork()
{
printf("This is a Task\n");
}
};
class PrintTask : public Task
{
public:
PrintTask(){}
~PrintTask(){}
public:
void doWork()
{
printf("This is a PrintTask\n");
}
};
class CacluateTask : public Task
{
public:
CacluateTask(){}
~CacluateTask(){}
public:
void doWork()
{
printf("This is a CacluateTask\n");
}
};
class CommTask : public Task
{
public:
CommTask(){}
~CommTask(){}
public:
void doWork()
{
printf("This is a CommTask\n");
}
};
#endif
接下来,我们需要稍微修改下我们的线程池代码,代码如下:
#ifndef __THREAD__H
#define __THREAD__H
#include <pthread.h>
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <vector>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include "Task.h"
enum threadState
{
THREAD_NORMAL,
THREAD_BUSY,
THREAD_KILL
};
class Thread
{
public:
Thread(Task* fun,const std::string threadName = std::string()):threadName(threadName)
{
this->fun = fun;
threadHandle = -1;
state = THREAD_NORMAL;
}
~Thread(){}
void setThreadFun(Task* fun)
{
this->fun = fun;
}
void run();
void stop();
private:
static void* start(void* arg)
{
Thread* thd = static_cast<Thread*>(arg);
printf("%s:",thd->threadName.c_str());
thd->fun->doWork();
return NULL;
}
public:
pthread_t threadHandle;
Task* fun;
std::string threadName;
threadState state;
};
class ThreadPool
{
public:
ThreadPool(const int threadNum):threadNum(threadNum)
{
threadPool.clear();
}
~ThreadPool()
{
}
void addThread(const int threadNum,Task* f);
void delThread(const int threadNum);
void schedule();
void startAll();
void stopAll();
Thread* assignThread();
private:
int threadNum;
std::vector<Thread*> threadPool;
};
#endif
再来看看我们的测试用例程序吧,代码如下:
#include "Thread.h"
#include "Task.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);
return 0;
}
总结
这篇博文主要是针对上篇博文的改进,主要的改进:将线程的回调函数全部抽象为对象,这样设计的好处就是易于管理不同的任务,以及将抽象与实现进行分离,从而提高模块的内聚度,在接下来的博文中,我们将会设计实现一个多线程多任务池的东西,将上面的东西进行整合,加深对线程池和任务池的理解,多谢了,
如果需要,请注明转载