运行 两个函数结合多处理和共享变量

Running two function together with multiprocessing and share variables

我使用了多处理,但我不知道该怎么做

逻辑:变量 sign 等于 0,函数调用 timer 计数 20 秒,每秒检查是否有符号等于 1 然后它会打印一些东西并打破循环,同时使用一个名为 waiting 的函数等待来自另一个库的输入,例如“discord”或“socket”因此,如果输入等于我的键,则将变量符号翻转为 1,这会影响第一个函数 timer

import multiprocessing
from time import sleep
sign = 0

def timer():
    for s in range(20):
        if sign == 1: # if the input is equal to the secret key then break the timer
            print("Yes!")
            break
        else:
            sleep(1) #if not then continue timing

def waiting():
    # maybe it waits for an input or a message from "discord or whatsapp"
    if message == "secret_key":
        sign = 1

p1 = multiprocessing.Process(target=timer)
p2 = multiprocessing.Process(target=waiting)
p1.start()
p2.start()

我在上面的评论中提到了它,但这里是你如何使用事件

import time
import multiprocessing as mp

def timer(exit_event):
    for s in range(20):
        if exit_event.is_set():
            print("Yes!")
            break
        else:
            time.sleep(1) #if not then continue timing

def waiting(exit_event):
    # maybe it waits for an input or a message from "discord or whatsapp"
    time.sleep(5)
    exit_event.set()
    

if __name__ == '__main__':
    exit_event = mp.Event()
    p1 = mp.Process(target=timer, args=(exit_event,))
    p2 = mp.Process(target=waiting, args=(exit_event,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

然而,使用 Event 的真正方法是 wait() 使其变为真。不需要睡眠循环。

def timer(exit_event):
    if exit_event.wait(timeout=20)
        # returns True if the event is True.  False if timed out
        print("Yes!")