-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy paththreadpool.py
More file actions
90 lines (65 loc) · 2.02 KB
/
Copy paththreadpool.py
File metadata and controls
90 lines (65 loc) · 2.02 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python
from Queue import Queue
from threading import Thread
# -------------------------------------
class ThreadPoolWorker(Thread):
# -------------------------------------
tasks_queue = None
# -------------------------------------
def __init__(self, tasks_queue):
# -------------------------------------
# Init
Thread.__init__(self)
self.tasks_queue = tasks_queue
# Start daemon thread
self.daemon = True
self.start()
# -------------------------------------
def __del__(self):
# -------------------------------------
pass
# -------------------------------------
def run(self):
# -------------------------------------
# Endless loop
while True:
# Fetch item from queue
func, args, kargs = self.tasks_queue.get()
# Execute task
#func(*args, **kargs)
try:
func(*args, **kargs)
except Exception, e:
print 'Args',func, args, kargs
print 'Exception',e
# Mark task as completed (remove from queue)
self.tasks_queue.task_done()
# -------------------------------------
class ThreadPool:
# -------------------------------------
num_threads = None
tasks_queue = None
DEFAULT_NUM_THREADS = 5
# -------------------------------------
def __init__(self, num_threads=DEFAULT_NUM_THREADS):
# -------------------------------------
# Init
self.num_threads = num_threads
self.tasks_queue = Queue(num_threads)
# Create 'num_threads' worker threads
for i in range(num_threads):
ThreadPoolWorker(self.tasks_queue)
# -------------------------------------
def enqueue(self, func, *args, **kargs):
# -------------------------------------
# Add a task to the queue
self.tasks_queue.put((func, args, kargs))
# -------------------------------------
def wait(self):
# -------------------------------------
# Wait for completion of all the tasks in the queue
self.tasks_queue.join()
# -------------------------------------
if __name__ == '__main__':
# -------------------------------------
print 'Error : This python script cannot be run as a standalone program.'