python - 在不同进程之间共享值的问题
问题描述
我有不同的进程等待事件发生(改变传感器的状态)我编写了如下代码:
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()
解决方案
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,))
对我来说,管道和队列是类似的机制,在多处理上下文中非常有用。如果您可以在您的情况下使用它们,我认为它们更适合数据交换(生产者、消费者),而不是进程之间的共享状态/价值。
推荐阅读
- javascript - 如何在微信小程序中将道具从一个组件传递到另一个组件
- android - 从 Firebase 数据库的特定字段首次启动应用程序时没有值或为零。通过建议我哪里出错来帮助我?
- asp.net - 抛出新的应用程序异常
- r - 如何从两个数据框中找到不同行数的近似接近值?
- regex - 如何使用 csv 文件仅替换文本文件中的某些字符串
- javascript - 创建像 shopify 这样的变体表
- python - 将索引列表转换为二维 numpy 数组的最快方法
- laravel - 在局域网上访问 Laravel
- ios - 我们如何将具有库的 sdk/Framework 共享给其他项目?
- flutter - http请求的单例类