在python中读取不断更新的列表

2024-09-27 20:17:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是从另一个进程不断更新的python列表中读取值,我在这里尝试编写一个最小的工作代码。 我在cfg.py中定义了一个全局数组作为

def initialize():
    global infrared_frames
    global depth_frames
    infrared_frames = []
    depth_frames = []

main.py开始,一个线程在该数组中追加一个随机值,而主线程休眠10秒,然后从该数组中读取该值。这是代码-

from multiprocessing import Process
import random
import time
import cfg

cfg.initialize()

def update_array():
    while True:
        cfg.infrared_frames.append(random.random())

p1 = Process(target=update_array)
p1.start()
time.sleep(10)
print('starting to read array')
print(cfg.infrared_frames)
for a in cfg.infrared_frames:
    print(a)

不幸的是,当我尝试在循环之前和time.sleep()调用之后打印数组时,数组仍然为空,但p1进程正在运行。为什么我不能读取数组? 抱歉,如果这是一个简单的问题,我的知识是有限的,当谈到线程在python中 提前谢谢。 T


Tags: 代码pyimportframestime进程defrandom
1条回答
网友
1楼 · 发布于 2024-09-27 20:17:31

在多处理中添加和使用数据的一个好方法是使用Queue

一个简单的工作示例:

import time
import multiprocessing as mp

from multiprocessing.queues import Queue


def fill_queue(queue):
    """ Endless process that fills the queue"""
    task = 0
    while True:
        time.sleep(1)
        queue.put(task)
        print(f"Added task {task}")
        task += 1


def read_queue(queue):
    """ Endless process that reads from the queue """
    while True:
        if queue.empty():
            time.sleep(0.2)
        else:
            print(f"Handling task: {queue.get()}")


if __name__ == '__main__':
    queue = Queue(maxsize=-1, ctx=mp.get_context())
    task_fill_queue = mp.Process(target=fill_queue, args=(queue,))
    task_fill_queue.start()

    read_queue(queue)

说明

fill_queue函数保持每秒向队列添加数据。然后由read_queue函数处理。它将每隔0.2秒检查队列中是否有新项目

相关问题 更多 >

    热门问题