阅读 python 中不断更新的列表
Reading an continuously updating list in 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
在多处理中添加和使用数据的一个好方法是使用 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 秒检查一次队列是否有新项目。
我的目标是从 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
在多处理中添加和使用数据的一个好方法是使用 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 秒检查一次队列是否有新项目。