简体   繁体   English

Python Queue 如何知道它将为空?

[英]How does Python Queue know it will be empty?

I would like to understand how a queue knows that it wont receive any new items.我想了解队列如何知道它不会收到任何新项目。 In the following example the queue will indefintely wait when the tputter thread is not started (I assume because nothing was put to it so far).在下面的示例中,当tputter线程未启动时,队列将tputter等待(我假设是因为到目前为止没有任何内容)。 If the tputter is started it waits between 'puts' until something new is there and as soon as everything is finished it stops.如果tputter启动,它会在“puts”之间等待,直到有新东西出现,一旦一切完成,它就会停止。 But how does the tgetter know whether something new will end up in the queue or not?但是tgetter如何知道新的东西是否会在队列中结束呢?

import threading
import queue
import time

q = queue.Queue()

def getter():
    for i in range(5):
        print('worker:', q.get())
        time.sleep(2)


def putter():
    for i in range(5):
        print('putter: ', i)
        q.put(i)
        time.sleep(3)

tgetter = threading.Thread(target=getter)
tgetter.start()
tputter = threading.Thread(target=putter)
#tputter.start()

A common way to do this is to use the "poison pill" pattern.一种常见的方法是使用“毒丸”模式。 Basically, the producer and consumer agree on a special "poison pill" object that the producer can load into the queue, which will indicate that no more items are going to be sent, and the consumer can shut down.基本上,生产者和消费者就一个特殊的“毒丸”对象达成一致,生产者可以将其加载到队列中,这将表明不会再发送任何项目,并且消费者可以关闭。

So, in your example, it'd look like this:所以,在你的例子中,它看起来像这样:

import threading
import queue
import time

q = queue.Queue()
END = object()

def getter():
    while True:
        item = q.get()
        if item == END:
           break
        print('worker:', item)
        time.sleep(2)


def putter():
    for i in range(5):
        print('putter: ', i)
        q.put(i)
        time.sleep(3)
    q.put(END)

tgetter = threading.Thread(target=getter)
tgetter.start()
tputter = threading.Thread(target=putter)
#tputter.start()

This is a little contrived, since the producer is hard-coded to always send five items, so you have to imagine that the consumer doesn't know ahead of time how many items the producer will send.这有点做作,因为生产者被硬编码为总是发送五个项目,所以您必须想象消费者不知道生产者将发送多少项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM