import threading from Queue import Queue import time MIN_JOBS JOB_CHUN

 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
import threading
from Queue import Queue
import time
MIN_JOBS = 5
JOB_CHUNK = 5
WORKERS = 5
JOBS = range(100)
def master(q):
iterator = iter(JOBS)
while True:
try:
if q.qsize() < MIN_JOBS:
for x in xrange(JOB_CHUNK):
item = iterator.next()
q.put('Item %d' % item)
except StopIteration:
for x in xrange(WORKERS):
q.put(None)
return
else:
time.sleep(0.01)
def worker(q):
while True:
job = q.get(False)
if job is None:
return
else:
print threading.currentThread(), job
time.sleep(0.1)
queue = Queue()
threads = []
threading.Thread(target=master, args=[queue]).start()
for x in xrange(WORKERS):
t = threading.Thread(target=worker, args=[queue])
threads.append(t)
t.start()
for t in threads:
t.join()