基于pthread的线程池,C++实现(4)

然后就是你自己真正想运行的JOB类了,这里我设计了一个JOB基类和派生类,应用中不一定要这样做,只是为了方便扩展

BaseJob.h

#ifndef BASEJOB_H_
#define BASEJOB_H_

#include "MyThread.h"

class BaseJob {
public:
 BaseJob();
 virtual ~BaseJob();

MyThread*  GetWorkThread(void){return m_pWorkThread;}
 void   SetWorkThread(MyThread* pWorkThread){m_pWorkThread = pWorkThread;}

virtual void Run(void* ptr) = 0;
private:
 MyThread* m_pWorkThread;
};

#endif /* BASEJOB_H_ */

BaseJob.cpp

#include "BaseJob.h"

BaseJob::BaseJob() {
 // TODO Auto-generated constructor stub

}

BaseJob::~BaseJob() {
 // TODO Auto-generated destructor stub
}

DetailJob.h

#ifndef DETAILJOB_H_
#define DETAILJOB_H_

#include "BaseJob.h"
#include <stdio.h>

class DetailJob: public BaseJob {
public:
 DetailJob();
 virtual ~DetailJob();

void Run(void* jobdata){
  printf("this is the job %d\n",*(int*)jobdata);
 }
};

#endif /* DETAILJOB_H_ */

DetailJob.cpp

#include "DetailJob.h"

DetailJob::DetailJob() {
 // TODO Auto-generated constructor stub

}

DetailJob::~DetailJob() {
 // TODO Auto-generated destructor stub
}

最后是main.cpp

#include <iostream>
#include "DetailJob.h"
#include "MyThreadPool.h"
using namespace std;

int main(int argc, char** argv){
 MyThreadPool* tp = new MyThreadPool(3);
 int i=0;
 for(; i<5; i++){
  DetailJob* job = new DetailJob();
  tp->Run(job, &i);
 }
 sleep(10);
 return 0;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/cf451b32c77072aa7ded15c12e72f994.html