-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy paththread_pool.cpp
101 lines (84 loc) · 2.38 KB
/
thread_pool.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/***********************************************************************
* Copyright (c) 2012, Baidu Inc. All rights reserved.
*
* Licensed under the BSD License
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* license.txt
*********************************************************************/
#include <iostream>
#include "thread_pool.h"
#include "thread_manager.h"
namespace bgcc {
/**
* @class ThreadPoolRunner
* @brief 线程池任务类型
*/
class ThreadPool::ThreadPoolRunner : public Runnable {
public:
/**
* @brief 线程池构造函数
* @param tp 线程池
* @return
*/
ThreadPoolRunner(ThreadPool* tp);
/**
* @brief 执行体
* @param
* @return
*/
virtual int32_t operator()(void* param);
private:
ThreadPool* _tp;
};
ThreadPool::ThreadPoolRunner::ThreadPoolRunner(ThreadPool* tp) : _tp(tp) {
}
int32_t ThreadPool::ThreadPoolRunner::operator()(void* param) {
while (true) {
RunnableSharedPointer pr;
_tp->_tasks.get(pr, BGCC_SEMA_WAIT_INFINITE);
if (pr.is_valid()) {
(*pr)();
}
}
return 1;
}
ThreadPool::ThreadPool() : _state(UNINITIALIZED) {
}
ThreadPool::~ThreadPool() {
terminate();
}
int ThreadPool::init(int nThreads) {
int ret = 0;
if (UNINITIALIZED == _state) {
_state = INITIALIZED;
addWorker(nThreads);
}
return ret;
}
bool ThreadPool::addTask(RunnableSharedPointer pr) {
return 0 == _tasks.put(pr);
}
bool ThreadPool::join() {
return _threadGroup.join();
}
size_t ThreadPool::size() {
return _threadGroup.size();
}
bool ThreadPool::terminate() {
return _threadGroup.terminateAll();
}
int ThreadPool::addWorker(int nWorker) {
int ret = 0;
for (int i = 0; i < nWorker; ++i) {
SharedPointer<Thread> workerThread = ThreadManager::createThread(
RunnableSharedPointer(new ThreadPoolRunner(this)));
if (workerThread.is_valid()) {
_threadGroup.addThread(workerThread);
++ret;
}
}
return ret;
}
}