有没有办法 - 内置或其他 - 来检测特定项目是否已经出列?
假设我知道itemX
已经出列,我只想执行一项操作。
q = queue.Queue()
q.put(itemX)
# Now I want to block-wait or get a callback or poll when `itemX` has been dequeued
我如何设置回调/阻止等待/轮询?
答案 0 :(得分:0)
好吧,由于队列不限于容纳唯一值,因此您需要找到一种方法来唯一地标记队列中的每个条目以使它们区别开来。这似乎是跟踪队列并在离开队列时抓住ItemX的唯一可行方法
答案 1 :(得分:0)
队列并非专门针对该功能而设计,但如果它适合您的用例,您可以使用单元素队列执行类似的操作:
from threading import Thread
from queue import Queue
import time
N = 5
def f(q):
for i in range(N):
print('t2: waiting for element from t1...')
time.sleep(1)
i = q.get()
print('t2: got {}...'.format(i))
q = Queue(1)
t = Thread(target=f, args=(q,))
t.start()
for i in range(N):
print('t1: putting item {}.'.format(i))
q.put(i)
q.put(None)
q.get()
print('t1: t2 got element, continuing')
t.join()
print('done')
输出:
t2: waiting for element from t1...
t1: putting item 0.
t2: got 0...
t2: waiting for element from t1...
t1: t2 got element, continuing
t1: putting item 1.
t2: got 1...
t2: waiting for element from t1...
t1: t2 got element, continuing
t1: putting item 2.
t2: got 2...
t2: waiting for element from t1...t1: t2 got element, continuing
t1: putting item 3.
t2: got 3...
t2: waiting for element from t1...
t1: t2 got element, continuing
t1: putting item 4.
t2: got 4...t1: t2 got element, continuing
done
但是,它并不完全确定,它依赖于生产者线程的q.get()
和q.put(None)
之间没有运行q.get()
的消费者线程。