Python队列块超时不超时-知道为什么吗?

2024-05-16 02:50:14 发布

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

我希望下面的python代码将在控制台输出中打印“Timeout:”。

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

预期的队列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中的Python2.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)

Tags: testselftimetimeoutstartnumendt1
1条回答
网友
1楼 · 发布于 2024-05-16 02:50:14

好吧,想想这个:

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

撇开这一点,您永远不应该依赖于Queue.empty()方法。参见文档:

If empty() returns True it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returns False it doesn’t guarantee that a subsequent call to get() will not block.

然而,在这样一个简单的上下文中,它是“相当可靠的”;—)现在您的超时怎么可能发生?如果且仅当队列为空时尝试.get()时。但当队列为空时,您永远不会执行.get(),因为:

if not myQueue.empty():

测试!实际上,你问的是:

I only try to do .get() when I'm sure something is on the queue. So I'm sure .get() will succeed immediatey. So why doesn't it ever time out?

移除

if not myQueue.empty():

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

相关问题 更多 >