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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值