the test code is very simple:
import threading, Queue
import time, random
class Worker(threading.Thread):
def __init__(self, index, queue):
threading.Thread.__init__(self)
self.index = index
self.queue = queue
def run(self):
while 1:
time.sleep(random.random())
item = self.queue.get()
if item is None:
break
print "index:", self.index, "task", item, "finished"
self.queue.task_done()
queue = Queue.Queue(0)
for i in range(2):
Worker(i, queue).start()
for i in range(10):
queue.put(i)
for i in range(2):
queue.put(None)
print "Main OK"
and the result is a little different every time i run it, here is just one :
Main OK
index: 1 task 0 finished
index: 0 task 1 finished
index: 0 task 2 finished
index: 1 task 3 finished
index: 1 task 4 finished
index: 0 task 5 finished
index: 1 task 6 finished
index: 0 task 7 finished
index: 1 task 8 finished
index: 1 task 9 finished
IMO when the main thread is terminated, "Main OK" will be printed, then the first thread will be executed until it comes into time.sleep(random.random()), then the first thread will sleep, and the second thread will continue. same to the first thread, the second thread will sleep when run into time.sleep(random.random()), then the first thread will continue again. and it will print index:0 task 0 finished right after Main OK, but in reality what follows Main OK is index: 1... not index: 0...! why? and it seems that the Queue doesnt run as normal multi-thread, sometimes the same index thread will execute three times or more continuously! what intheworld does the Queue mechanism works? any help appreciated!