#coding: utf-8
import Queue
import threading
class MyThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.setDaemon(True)
self.queue = queue
def run(self):
while True:
try:
task = self.queue.get(timeout=2)
print 'task: %s' % task
# 这里可以处理task
except Exception, err:
break
if __name__ == '__main__':
threads = []
q = Queue.Queue()
for i in xrange(3):
thread = MyThread(q)
threads.append(thread)
for t in threads:
t.start()
for i in xrange(30):
q.put(i)
for t in threads:
t.join()
print '====== done ======'
消費者join一下試試,然後你判斷一下條件,如果queue為空的時候,循環break
如果self.Queue為空的話, self.Queue.get() 會拋出 Queue.Empty 異常,這時候線程會退出,這時候都沒有工作線程了。
在run()方法的while循環裡面增加try...except捕捉該異常試試。程式碼大概如下:
================================================= ======================
首先:對於你說的mysql不支持多線程寫入問題,我簡單寫了個驗證程序,結論是mysql支持多執行緒寫入的(註:實際工作中在多執行緒中往db中寫入數據,需要加入鎖機制,這裡簡化了),程式碼如下:
另外:因為不清楚你的程式碼的具體細節,所以不能完全定位問題,我自己寫了個模擬程序,沒有出現你的那種情況,希望對你有幫助,程式碼如下: