用于存储和检索数据的Python队列线程安全
我知道这个问题的答案如下: 队列模块实现了多生产者、多消费者队列,因此是安全的 在一个问题中 然而,在我的应用程序中,Python的队列和Numpy模块出现了一种奇怪的行为。我使用服务器在线程安全队列中存储2个图像,然后检索图像进行处理(我必须找到包含车辆的像素,然后重建图像) 我的实施是:用于存储和检索数据的Python队列线程安全,python,multithreading,numpy,queue,store,Python,Multithreading,Numpy,Queue,Store,我知道这个问题的答案如下: 队列模块实现了多生产者、多消费者队列,因此是安全的 在一个问题中 然而,在我的应用程序中,Python的队列和Numpy模块出现了一种奇怪的行为。我使用服务器在线程安全队列中存储2个图像,然后检索图像进行处理(我必须找到包含车辆的像素,然后重建图像) 我的实施是: # Storing the 2 images in a thread-safe queue. def server_callback(queue, name, data): queue.put(na
# Storing the 2 images in a thread-safe queue.
def server_callback(queue, name, data):
queue.put(name, data)
# Retrieving images from server.
# This runs a background service, which retrieves the images
# and uses the "server_callback" method to store them in the queue.
server.tick(server_callback)
# Retrieving images from queue. It blocks the queue (for 1.0 sec max).
camera_data = {'segmentation':None, 'depth':None}
for i in range(2):
name, data = queue.get(True, 1.0)
camera_data[name] = data
# Images are retrieved, without raising any exception.
seg_data = camera_data['segmentation']
dep_data = camera_data['depth']
# Retrieving pixels that contain blue color.
# return np.where(np.all(seg_data == VEHICLE_COLOR, axis=2))
vehicle_indices = image_data_utils.get_vehicle_indices(seg_data)
# WARNING!
# It should print the correct number of pixels that contain the Vehicle's color.
print( vehicle_indices[0].shape[0] )
# Re-constructing the image with only the vehicle, based on vehicle's indices and a grayscale image.
observation = image_data_utils.get_normalized_depth_of_vehicles(dep_data, vehicle_indices)
# Displaying the images.
seg_data = camera_data['segmentation']
dep_data = camera_data['depth']
cv2.imshow('segmentation', seg_data)
cv2.imshow('depth', dep_data)
cv2.imshow('observation', observation)
cv2.waitKey()
cv2.destroyAllWindows()
通过此尝试,numpy模块仅检测车辆像素的一半。为了检测每一个
像素我需要强制程序休眠一段时间:
# Images are retrieved, without raising any exception.
seg_data = camera_data['segmentation']
dep_data = camera_data['depth']
time.sleep(3)
# Continue processing the images ...
通过在从队列中检索图像后强制程序休眠,可以正确构造(右上)中所需的图像
(右上)中所需的图像构造错误,从队列中检索图像后试图立即处理这些图像。它只检测所需像素的一半
我真的不明白。我已经实现了线程安全队列,如python的3.7文档中所述。主线程如何仅从队列中检索图像的一半?我能找到的唯一原因是,服务器的线程试图将映像存储在队列中,而主线程则试图将其弹出。但是,由于队列被阻塞,因此不可能执行此操作。
有人遇到过类似的事情吗
提前非常感谢您阅读本文