-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathThreadPool.py
More file actions
71 lines (56 loc) · 1.49 KB
/
Copy pathThreadPool.py
File metadata and controls
71 lines (56 loc) · 1.49 KB
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
#coding=utf-8
import threading, Queue, time, sys
Qin = Queue.Queue()
Qout = Queue.Queue()
Qerr = Queue.Queue()
Pool = []
def report_error():
Qerr.put(sys.exc_info()[:2])
def get_all_from_queue(Q):
try:
while True:
yield Q.get_nowait()
except Queue.Empty:
raise StopIteration
def do_work_from_queue():
while True:
command, item = Qin.get()
if command == 'stop':
break
try:
if command == 'process':
result = 'new' + item
else:
raise Value, 'Unknown command %r' % command
except:
report_error()
else:
Qout.put(result)
def make_and_start_thread_pool(number_of_threads_in_pool=5, daemons=True):
for i in range(number_of_threads_in_pool):
new_thread = threading.Thread(target=do_work_from_queue)
new_thread.setDaemon(daemons)
Pool.append(new_thread)
new_thread.start()
def request_work(data, command='process'):
Qin.put((command, data))
def get_result():
return Qout.get()
def show_all_results():
for result in get_all_from_queue(Qout):
print 'Result:', result
def show_all_errors():
for etyp, err in get_all_from_queue(Qerr):
print 'Error:', etyp, err
def stop_and_free_thread_pool():
for i in range(len(Pool)):
request_work(None, 'stop')
for existing_thread in Pool:
existing_thread.join()
del Pool[:]
if __name__ == '__main__':
for i in ('_ba',7,'_bo'): request_work(i)
make_and_start_thread_pool()
stop_and_free_thread_pool()
show_all_results()
show_all_errors()