1

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()
  • 1
    Please do use mutex with condition variable for your application. Either you have to work with semaphore or mutex with shared resources. – iamniki Dec 03 '21 at 23:41
  • can you explain mutex or redirect me to a link – Joseph Yosoevsky Dec 03 '21 at 23:55
  • It's actually take a whole day or two. But it's always better to go through multithreading and multiprocessing concepts and better to know what exactly you trying to do. So, here I will provide you a link where it gives you complete overview of it. https://www.toptal.com/python/beginners-guide-to-concurrency-and-parallelism-in-python – iamniki Dec 03 '21 at 23:58
  • Actually, in this case, you just need to use `multiprocessing.Event()`. Since your program is just testing to see if an "event" has happened, you can avoid using a semaphore or a mutex. Though you should learn what they are, anyway. – Frank Yellin Dec 04 '21 at 00:04

1 Answers1

2

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!")
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22