gpt4 book ai didi

python - 等待进程成语

转载 作者:太空狗 更新时间:2023-10-30 00:09:13 25 4
gpt4 key购买 nike

下面的成语有没有更好的写法:

while q.empty():      # wait until data arrives.
time.sleep(5)
while not q.empty(): # start consuming data until there is nothing left.
data = q.get() # this removes an item from the queue (works like `.pop()`)
# do stuff with data

qmultiprocessing.Queue() 的一个实例,尽管我认为上述构造也可以在其他地方找到。

我觉得必须有更好的方法来做到这一点..

最佳答案

默认情况下,如果您使用 .get(..),您将有一个阻塞队列。事实上,如果我们看一下 documentation :

<b>get([block[, timeout]])</b>
Remove and return an item from the queue. If optional args block is True (the default) and Timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Queue.Empty exception if no item was available within that time. Otherwise (block is False), return an item if one is immediately available, else raise the Queue. Empty exception (timeout is ignored in that case).

因此您可以安全地使用:

while True:
data = q.get()
# ... process data

因此无需进行“轮询”。一个简单的 .get(..) 通常会休眠,直到系统通知数据可用(尽管这可能取决于例如操作系统。

关于python - 等待进程成语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48207427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com