多处理两个都使用 time.sleep() 的函数

Multiprocessing two functions that both use time.sleep()

我正在开发一个带有 raspberry pi 的项目,我需要有两个并行的函数 运行ning,这两个函数都需要访问相同的 GPIO 引脚(它们需要打开 on/off 相同的泵)。

问题是功能 1 需要每 40 分钟访问一次这些泵,每次使用它们 5 分钟,而功能 2 需要每 3 小时访问一次,每次使用 5 分钟。我保持泵处于活动状态的方法是使用 time.sleep() 打开 GPIO 引脚,然后将其关闭。在功能使用泵后,他们需要将化学物质分配到水中并等待这些化学物质溶解(功能 1 等待 30 分钟,功能 2 等待 3 小时)。

我正在寻找并行 运行 这些函数的最佳方法,同时考虑到它们之间可能存在的 scheduling/timing 冲突。我希望 function1 能够使用泵,即使 function2 正在等待其化学物质溶解。我正在考虑使用一个全局变量来检查泵是否正在使用,以让函数知道它们需要等待才能访问这些泵,但经过一些测试后,我不确定这是否适用于多处理。

我设置了一些测试代码来模拟函数的时序。根据我的输出,似乎 function1 和 function2 都在同时分配它们的化学品。非常感谢任何想法或建议。

import time
from multiprocessing import Process

pumpInUse = False #used to store the state of the pumps

def function1():
    global pumpInUse
    if pumpInUse is False:
        print "starting function1 test @ " + str((time.strftime("%H:%M:%S")))
        pumpInUse = True #turn pump on
        time.sleep(5)  #simulating 5 minutes of pump use
        print "function1 test complete @ " + str((time.strftime("%H:%M:%S")))
        pumpInUse = False #turn pump off
        function1status = 'bad' #simulating bad chemical level

        if function1status == 'bad':
            print "dispense chemicals @ " + str((time.strftime("%H:%M:%S")))
            time.sleep(10) #simulate wait 30 minutes after chemcials dispensed
            print "checking water @ " + str((time.strftime("%H:%M:%S")))
            pumpInUse = True
            time.sleep(5) #simulating 5 minutes of pump use
            print "function1 complete @ " + str((time.strftime("%H:%M:%S")))
            pumpInUse = False

def function2():
    global pumpInUse
    if pumpInUse is False:
        print "starting function2 test @ " + str((time.strftime("%H:%M:%S")))
        pumpInUse = True
        time.sleep(5) #simulating 5 minutes of pump use
        print "function2 test complete @ " + str((time.strftime("%H:%M:%S")))
        pumpInUse = False
        function2status = 'bad' #simulating bad chemical level

        if function2status == 'bad':
            print "dispense chemicals @ " + str((time.strftime("%H:%M:%S")))
            time.sleep(30) #simulate wait 3 hours after chemicasl dispensed
            print "checking water @ " + str((time.strftime("%H:%M:%S")))
            pumpInUse = True
            time.sleep(5) #simulating 5 minutes of pump use
            print "function2  complete @ " + str((time.strftime("%H:%M:%S")))
            pumpInUse = False

if __name__ == '__main__':
    #while True:
        p1 = Process(target=function1)
        p2 = Process(target=function2)
        p1.start()
        p2.start()
        p1.join()
        p2.join()

您正在查找线程(或进程)synchronization primitives,在本例中,可能是 Lockfunction1 将获取阻塞锁并在完成后释放它。当function2尝试获取锁时,会自动等待直到锁被释放。