我希望以下 python 代码将在控制台输出中打印“超时:”。

它有一个生产对象的线程。消费者线程将获取排队的对象并将其打印出来。

预期的 Queue Get() 超时没有发生。知道为什么吗?

输出是:(没有预期的“超时:”打印输出。)

1390521788.42  Outputting: o={'test': 2, 'sName': 't1'}
1390521791.42  Outputting: o={'test': 3, 'sName': 't1'}
1390521794.42  Outputting: o={'test': 4, 'sName': 't1'}
1390521797.42  Outputting: o={'test': 5, 'sName': 't1'}
end while sName=t1

这是在 Linux 中使用 Python 2.7 测试的。
import threading, Queue, time

class ProduceThread(threading.Thread):
    def __init__ (self, start_num, end, q, sName, nSleep=1):
        self.num = start_num
        self.q = q
        threading.Thread.__init__ (self)
        self.m_end = end;
        self.m_sName = sName;
        self.m_nSleep = nSleep;

    def run(self):
        o = {};
        o['sName'] = self.m_sName;
        while True:
            if self.num != self.m_end:
                self.num += 1
                o['test'] = self.num;
                # self.q.put(self.num)
                self.q.put(o)
                time.sleep(self.m_nSleep)
            else:
                break
        print "end while sName=%s" % (self.m_sName);

myQueue = Queue.Queue()
myThread = ProduceThread(1, 5, myQueue, 't1', 3); myThread.start()
# myThread2 = ProduceThread(1, 5, myQueue, 't2', 3); myThread2.start()
# myThread3 = ProduceThread(1, 5, myQueue, 't3', 3); myThread3.start()

def Log(s):
    t = time.time();
    print "%s  %s" %(t, s)

################################################################
#  Consumer Loop
while True:
    if not myQueue.empty():
        try:
            o = myQueue.get(block=True, timeout=1)
            Log( "Outputting: o=%s" % (o));
        except:
            ###### I expect the Timeout to happen here. But it is not.
            Log( "Timeout: " );
            pass;
    # time.sleep(1)

最佳答案

嗯,想想这个:

if not myQueue.empty():
    try:
        o = myQueue.get(block=True, timeout=2)
        Log( "Outputting: o=%s" % (o));

撇开你永远不应该依赖 Queue.empty() 方法。查看文档:



但是,在如此简单的上下文中,它“非常可靠”;-) 现在您的超时怎么可能发生?当且仅当您的队列为 时进行 .get() 尝试。但是当您的队列为空时,您永远不会执行您的 .get(),因为您的:
if not myQueue.empty():

测试!实际上,您是在问这个:



去除那个
if not myQueue.empty():

完全声明然后它最终会超时。

关于Python 队列块超时不会超时 - 知道为什么吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21320621/

10-14 11:26
查看更多