There are 101 things stored in THINGS
variable.
The code declares 101 threads and executes them all at once instantly all at the same time.
I wonder if we can limit the number of the active threads to just 12.
At first only 12 threads should pick their 12 THINGS to process. The rest of the threads should be waiting for the first 12 to finish their jobs. When the first 12 threads are all done then the next 12 threads would pick up the next 12 THINGS to process. And so one.
Would it be possible?
import Queue
import threading, time
class MyThread(threading.Thread):
def __init__(self, theQueue=None):
threading.Thread.__init__(self)
self.theQueue=theQueue
def run(self):
thing=self.theQueue.get()
self.process(thing)
self.theQueue.task_done()
def process(self, thing):
time.sleep(1)
print 'processing %s'%thing.name
queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
THREADS=[]
for thing in THINGS:
thread=MyThread(theQueue=queue)
thread.name = thing
THREADS.append(thread)
thread.start()
for thread in THREADS:
queue.put(thread)