執行緒池的c 實現

2021-08-20 01:34:05 字數 1734 閱讀 1788

emmmm,寫這個的主要目的是為了加深對互斥鎖和條件變數的理解,只看unix網路程式設計不實踐一下老覺得心裡沒點底,正好這個東西能練一下而且面試好像也有問到,就手動實現了一下.

執行緒池運用的設計模式是命令模式,其原理基本上都能查到這裡就不多說了.直接上**好了.

首先是任務類 task.h

#ifndef task_h

#define task_h

#include using namespace std;

class task;

#endif

task.cc

#include "task.h"

void task::setname(string taskname)

執行緒池管理類 pthreadpoll.h

#ifndef pthreadpoll_h

#define pthreadpoll_h

#include #include #include "task.h"

using namespace std;

class pthreadpoll;

#endif

pthreadpoll.cc

#include "pthreadpoll.h"

#include #include queuepthreadpoll::q;

pthread_mutex_t pthreadpoll::mutex;

pthread_cond_t pthreadpoll::cond;

vectorpthreadpoll::pthread_id;

bool pthreadpoll::flag;

pthreadpoll::pthreadpoll(int s):size(s)

void pthreadpoll::create()

return null;

}int pthreadpoll::getsize()

pthreadpoll::~pthreadpoll()

void pthreadpoll::destroy()

while(1)

printf("success\n");

}

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變數參照了書上的實現,雖然其他部落格大多沒有這麼寫,但是這個地方我覺得書上寫的還是很精闢的.強烈推薦看下這本書.當然博主的**可能還有紕漏,我只測試過這個樣例,歡迎指出錯誤,謝謝.

c 執行緒池的實現

github 傳送門 1.使用例項 測試job寫檔案 class job public wjob job job 1 void run endif 3.wthread 對wthread的封裝,主要在於將之與wjob繫結以完成任務,並與執行緒池繫結,在任務結束後將自己放回空閒佇列 每乙個執行緒都執行r...

C 執行緒池的實現

寫了乙個簡易執行緒池,原理簡單介紹下,就是設定乙個任務佇列queue,用來放要執行的函式,還有乙個執行緒陣列vector,用來存放所有的執行緒。執行緒建立以後就存放在相應的vector裡,空閒的執行緒去queue裡去取要執行的函式位址,在run函式中執行,假如乙個執行緒的run函式執行好後,發現佇列...

c 執行緒池實現(四)執行緒池實現

前面已經說到了同步佇列的實現,下面來看執行緒池的實現。ifndef include threadpool define include threadpool include include include include include syncqueue.hpp namespace mythrea...