首页 > 解决方案 > 在不同进程之间共享值的问题

问题描述

我有不同的进程等待事件发生(改变传感器的状态)我编写了如下代码:

def Sensor_1():
    wait_for_change_in_status
    set counter to X
    activate_LED_process.start()

def Sensor_2():
    same function
def Sensor_3():
    same function

def LED():
    start LEDs
    while counter > 0:
        counter -= 1
        time.sleep(1)
    turn off LEDs
    active_LED_process.join()

...

if __name__ == '__main__':
    Sensor_1_process = multiprocessing.Process(target=Sensor_1)
    Sensor_2_process = same
    Sensor... you get it.
    activate_LED_process = multiprocessing.Process(target=LED)

现在我被计数器值的交换所困扰。具有不同的进程能够将计数器更改为特定值。每个传感器都应该能够重置计数器的值。LED 进程应该能够“对计数器进行倒计时”并在计数器达到零时做出反应。

什么是适当的解决方案?我读到了值、数组、管道和队列。对于值和数组,我找不到好的文档。管道似乎只适用于两个进程。队列似乎不仅拥有一个值(我将队列与列表进行比较 - 这是正确的吗?)

import RPi.GPIO as GPIO
import time
import multiprocessing
import sys
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
LED_time = 40  #time how long LEDs stay active (not important at this point)

def Sens_GT():
    name = multiprocessing.current_process().name
    print(name, 'Starting')
    while True:
        GPIO.wait_for_edge(25, GPIO.FALLING)
        time.sleep(0.1)
        print("Open")
        LED_count = multiprocessing.value('i', 40) #For later: implementation of LED_time as a variable
        print(LED_count) #For checking if the counter is set properly
"""
Missing code:

    if "Process is already running":
        go on
    else:
        Count_proc.start()

"""
    print(name, 'Exiting') #Shouldn't happen because of the "while True:"

"""
Missing code:

def Sens_GAR():

def Sens_HT():

"""

def Count():
    name = multiprocessing.current_process().name
    print(name, 'Starting')

"""
Missing code:

Import counter value

"""

    while countdown > 0:
        print(countdown)
        time.sleep(1)
        LED_count -= 1
    print(name, 'Exiting')
    GPIO.cleanup()           # clean up GPIO on normal exit
    Count_proc.join()
    sys.exit(1)

if __name__ == '__main__':
    value_count = mutliprocessing.value('i', 0)
    lock = Lock()

    Sens_GT_proc = multiprocessing.Process(target=Sens_GT)
    Count_proc = multiprocessing.Process(target=Count)

    Sens_GT_proc.start()
    Sens_GT_proc.join()

标签: pythonpython-3.xmultiprocessingsharing

解决方案


Value 似乎是您的用例的不错选择。但是,您没有以正确的方式使用它。

使用 实例化一个值后multiprocessing.Value(),您必须将该对象作为参数传递给您的子流程,如多处理指南中所示。

所以你的代码应该是这样的:

def Sens_GT(counter):
    ...
    counter = 40
    ...

def Count(counter):
    ...
    while counter > 0:
        counter -= 1
        time.sleep(1)
    ...
...

if __name__ == '__main__':
    value_count = mutliprocessing.value('i', 0)

    Sens_GT_proc = multiprocessing.Process(target=Sens_GT, args=(value_count,))
    Count_proc = multiprocessing.Process(target=Count, args=(value_count,))

对我来说,管道和队列是类似的机制,在多处理上下文中非常有用。如果您可以在您的情况下使用它们,我认为它们更适合数据交换(生产者、消费者),而不是进程之间的共享状态/价值。


推荐阅读