python queue task_done()问题

2024-04-19 12:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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中的多线程有什么我遗漏的吗?


Tags: self元素taskget队列queueconsumerinit