スレッドプールのc++実装

3382 ワード

Emmmm、これを書く主な目的は、反発ロックや条件変数の理解を深めるためで、UNIXのネットプログラミングを見ているだけでは実践しないといつも心が落ち着かないので、ちょうどこれが練習できるし、面接でも質問があるようで、手動で実現しました.
スレッドプールが運用する設計モードはコマンドモードであり,その原理は基本的にここまで調べられるので多くは言わない.直接コードをつけたほうがよい.
まずタスククラスTaskです.h
#ifndef TASK_H
#define TASK_H

#include 
using namespace std;

class Task{
protected:
	string name;
public:
	virtual void run()=0;
	void setname(string taskname);
};

#endif

Task.cc
#include "Task.h"

void Task::setname(string taskname){
	name=taskname;
}

スレッドプール管理クラスPthreadpoll.h
#ifndef PTHREADPOLL_H
#define PTHREADPOLL_H

#include 
#include 
#include "Task.h"

using namespace std;

class Pthreadpoll{
private:
	static queueq;
	static pthread_mutex_t mutex;
	static pthread_cond_t cond;
	static vectorpthread_id;
	static bool flag;
	int size;
	void create();
protected:
	static void* threadfunc(void *args);

public:
	Pthreadpoll(int s);
	void addtask(Task *task);
	int getsize();
	void destroy();
	~Pthreadpoll();
};

#endif

Pthreadpoll.cc
#include "Pthreadpoll.h"
#include 
#include 

queue Pthreadpoll::q;
pthread_mutex_t Pthreadpoll::mutex;
pthread_cond_t Pthreadpoll::cond;
vector Pthreadpoll::pthread_id;
bool Pthreadpoll::flag;

Pthreadpoll::Pthreadpoll(int s):size(s){
	create();	
}

void Pthreadpoll::create(){
	pthread_t *id;
	for(int i=0;irun();
		delete task;
		pthread_mutex_unlock(&mutex);
	}
	return NULL;
}

int Pthreadpoll::getsize(){
	return q.size();
}

Pthreadpoll::~Pthreadpoll(){
	destroy();
}

void Pthreadpoll::destroy(){
	flag=true;
	pthread_cond_broadcast(&cond);
	for(int i=0;i

メイン関数main.cc
#include "Pthreadpoll.h"
#include 
#include 
#include 

using namespace std;
class Texttask:public Task{
public:
	virtual void run(){
		cout<setname(name);
		pthreadpoll.addtask(task);
	}
	while(1){
		if(!pthreadpoll.getsize())
			break;
	}
	printf("success
"); }

makefile
objects=Task.o Pthreadpoll.o main.o

pthreadpoll.out:$(objects)
	g++ -o pthreadpoll.out $(objects) -lpthread

main.o:main.cc Pthreadpoll.o Task.o
	g++ -g -c main.cc

Pthreadpoll.o:Pthreadpoll.cc Pthreadpoll.h Task.o
	g++ -g -c Pthreadpoll.cc

Task.o:Task.cc Task.h
	g++ -g -c Task.cc

.PHONE:clean
clean:
	rm pthreadpoll.out $(objects)

その中の実装は多くの文章を参考にしすぎて、それからロックと反発変数の運用は私はUNIXネットワークのプログラミングをよく読んだことがあります.その中のdosignal変数は本の実装を参照しています.他のブログの多くはそう書いていませんが、この場所では本に書いてあるのは精巧だと思います.この本を読むことを強くお勧めします.もちろん、ブロガーのコードには漏れがあるかもしれません.私はこのサンプルしかテストしたことがありません.間違いを指摘してください.ありがとうございます.