线程池的原理大家都知道,直接上代码了^_^
test.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include "Thread.h" #include <iostream> #include <cstdio> #include <cstdlib> class CMyTask: public CTask { public: CMyTask(){} inline int Run() { printf("%s\n", (char*)this->m_ptrData); sleep(10); return 0; } }; int main() { CMyTask taskObj; char szTmp[] = "this is the first thread running"; taskObj.SetData((void*)szTmp); CThreadPool threadPool(10); for(int i = 0; i < 20; i++) { threadPool.AddTask(&taskObj); } while(1) { printf("there are still %d tasks need to handle\n", threadPool.getTaskSize()); if (threadPool.getTaskSize() == 0) { if (threadPool.StopAll() == -1) { printf("Now I will exit from main\n"); exit(0); } } sleep(2); } return 0; } |
近期评论