forked from TinaryTree/damaiTi9
-
Notifications
You must be signed in to change notification settings - Fork 1
/
threadpool.py
79 lines (61 loc) · 2.2 KB
/
threadpool.py
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
from threading import Thread
from logging import getLogger
from six.moves.queue import Queue
from threading import Lock
import gc
import time
class WorkerThread(Thread):
def __init__(self, task_queue, *args, **kwargs):
super(WorkerThread, self).__init__(*args, **kwargs)
self._task_queue = task_queue
self._succ_task_num = 0
self._fail_task_num = 0
self._ret = list()
def run(self):
while True:
func, args, kwargs = self._task_queue.get()
try:
ret = func(*args, **kwargs)
self._succ_task_num += 1
self._ret.append(ret)
except Exception as e:
print(e)
self._fail_task_num += 1
self._ret.append(e)
finally:
self._task_queue.task_done()
if self._task_queue.empty():
break
def get_result(self):
return self._succ_task_num, self._fail_task_num, self._ret
class SimpleThreadPool:
def __init__(self, num_threads=5):
self._num_threads = num_threads
self._queue = Queue(2000)
self._lock = Lock()
self._active = False
self._workers = list()
self._finished = False
def add_task(self, func, *args, **kwargs):
if not self._active:
with self._lock:
if not self._active:
self._active = True
for i in range(self._num_threads):
w = WorkerThread(self._queue)
self._workers.append(w)
w.start()
self._queue.put((func, args, kwargs))
def release(self):
while self._queue.empty() is False:
time.sleep(1)
def wait_completion(self):
self._queue.join()
self._finished = True
def get_result(self):
assert self._finished
detail = [worker.get_result() for worker in self._workers]
succ_all = all([tp[1] == 0 for tp in detail])
return {'success_all': succ_all, 'detail': detail}
if __name__ == '__main__':
pool = SimpleThreadPool(2)