python task done_python queue task_done()问题
我對python多線程隊列有問題。我有一個腳本,其中producer從輸入隊列獲取元素,生成一些元素并將它們放入輸出隊列,consumer從輸出隊列獲取元素并打印它們:import threading
import Queue
class Producer(threading.Thread):
def __init__(self, iq, oq):
threading.Thread.__init__(self)
self.iq = iq
self.oq = oq
def produce(self, e):
self.oq.put(e*2)
self.oq.task_done()
print "Producer %s produced %d and put it to output Queue"%(self.getName(), e*2)
def run(self):
while 1:
e = self.iq.get()
self.iq.task_done()
print "Get %d from input Queue"%(e)
self.produce(e)
class Consumer(threading.Thread):
def __init__(self, oq):
threading.Thread.__init__(self)
self.oq = oq
def run(self):
while 1:
e = self.oq.get()
self.oq.task_done()
print "Consumer get %d from output queue and consumed"%e
iq = Queue.Queue()
oq = Queue.Queue()
for i in xrange(2):
iq.put((i+1)*10)
for i in xrange(2):
t1 = Producer(iq, oq)
t1.setDaemon(True)
t1.start()
t2 = Consumer(oq)
t2.setDaemon(True)
t2.start()
iq.join()
oq.join()
但是,每次我運行它時,它的工作方式都不同(給出異常,或者消費者不做任何工作)。我認為問題出在task_done()命令中,有人能解釋一下bug在哪里嗎?
我修改了消費類:class Consumer(threading.Thread):
def __init__(self, oq):
threading.Thread.__init__(self)
self.oq = oq
def run(self):
while 1:
e = self.oq.get()
self.oq.task_done()
print "Consumer get %d from output queue and consumed"%e
page = urllib2.urlopen("http://www.ifconfig.me/ip")
print page
現在,每個task_done()命令之后的使用者都應該連接到網站(這需要一些時間),但它不需要,相反,如果task_done()之后的代碼執行時間很短,它會運行,但如果很長,它不會運行!為什么?有人能解釋一下這個問題嗎?如果我把所有的東西都放在task_done()命令之前,那么我將從其他線程中阻塞隊列,這已經足夠愚蠢了。或者在python中的多線程有什么我遺漏的嗎?
總結
以上是生活随笔為你收集整理的python task done_python queue task_done()问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝牙之十一 AVRCP协议
- 下一篇: python抓取qq群消息,python