不同进程之间共享值的问题

Troubles with sharing values between different processes

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

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 进程应该能够 "countdown the counter" 并做出反应。

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

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()

Value 对于您的用例来说似乎是一个不错的选择。 但是,你没有正确使用它。

multiprocessing.Value() 实例化一个值后,您必须将对象作为参数传递给您的子流程,如 multiprocessing guide.

所示

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

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,))

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