pythonpython-3.xmultiprocessingpython-multiprocessingshared-variable

Running two function together with multiprocessing and share variables


i used multiprocessing but i don't know how to do it

the logic : a variable sign is equal to 0, with a function called timer count 20 seconds and each second check if sign is equal to 1 then it'll print something and breaks the loop, at the same time with a function called waiting waits for an input from another library as example "discord" or "socket" so if the input is equal to my key flip the variable sign to 1 and that affects the first function 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()

Solution

  • I mentioned it above in a comment, but here is how you would use an event

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

    However the real way to use an Event is to just to wait() for it to become true. No need for a sleep loop.

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