如何处理和保存来自传感器的连续数据

时间:2019-11-29 07:08:27

标签: python python-multiprocessing python-multithreading

示例:

我已经在汽车上安装了一个传感器,该传感器正在连续发送数据,现在,我必须处理(融合)来自传感器的连续数据,但同时过程将完成其执行,数据还将即将到来,如何存储过程需要时间来执行以备将来之用的即将到来的数据?

    sample code:

    buffer1=[]
    buffer2=[]

    def process_function(buffer):
        //processing

    while true:
        //data receiving continously
        buffer1.append(data)
        if len(buffer1)>0: process(buffer1)
        buffer2.append(data)

(while the process_function will take buffer1 to process, at the same time, the continuous data should be stored in buffer2 so that after finishing the process_function with buffer1 can process with buffer2 and repeat.)

1 个答案:

答案 0 :(得分:1)

您可以使用一个多处理队列和两个进程。一种用于生产者,一种用于消费者:

from multiprocessing import Process, Queue

def collection_sensor_values(mp_queue):
    fake_value = 0
    while True:
        mp_queue.put(f"SENSOR_DATA_{fake_value}")
        fake_value += 1
        time.sleep(2)

def process_function(mp_queue):
    while True:
        sensor_reading = mp_queue.get(block=True)
        print(f"Received sensor reading: {sensor_reading}")

q = Queue()
sensor_collector_process = Process(target=collection_sensor_values, args=(q,))
readings_process = Process(target=process_function, args=(q,))
all_procs = [sensor_collector_process, readings_process]

for p in all_procs:
    p.start()

for p in all_procs:
    # run until either process stops
    if p.is_alive():
        p.join()

for p in all_procs:
    if p.is_alive():
        p.terminate()