【发布时间】:2021-06-15 09:41:41
【问题描述】:
我正在尝试实现一个从套接字客户端接收图像的管道。我目前正在使用 python 队列(来自队列模块)来存储客户端发送的图像并由服务器读取。但我只对发送的最后一张图片感兴趣(添加到队列中)。我用于服务器的代码是:
import threading
from queue import Queue
CLIENTS = 2
queues = [Queue(1) for _ in range(CLIENTS)]
for i in CLIENTS:
threading.Thread(target=handle,args=(queues[i],)).start() # each client writes to its own queue
while True:
frames = [q.get() for q in queues]
问题在于,当队列已满时,put 方法(在客户端)会一直等待,直到队列满为止。我想要的是实现一些结构,以便当队列已满时,它只需弹出元素并从 get 方法添加新元素(线程安全)。这样队列(大小 1)总是收到最后一张图像。 我也在客户端尝试过:
with q.mutex:
if q.full:
q.queue.clear()
q.put(image)
但它卡在“q.put(image)”中。 有人可以帮我解决这个问题吗?
【问题讨论】:
标签: python multithreading queue