Search code examples
pythonpython-multiprocessing

How to do inter-process communication?


We are doing multiprocessing in Python3 on Raspberry Pi3. We do mask detection, people counting and cough detection in processes. We have 3 processes for now. All have been described as functions. (def mask (), .. def cough () etc.) They all work at the same time, there is no problem here. The problem is that as a 4th process, we want to write a alarm function according to the information from these 3 processes.

Our goal is to print an error on the screen if an unwanted situation occurs in these 3 detections (such as wrong mask use, too many people count.). 4. As a process, we cannot use the values returned by other functions with if-else commands under the alarm () function. I write the kind of summary of the code below. How can we use the data in the process? Now, alarm() does not work properly.

def mask():
      while True:
         if problem:
            return True

def cough():
      while True:
         if problem:           
            return True
def alarm():
      while True:
        if mask():
           print("Eror1")
        elif cough():
           print("Error2")

if __name__ == "__main__":
    p1 = multiprocessing.Process(target=cough,)
    p2 = multiprocessing.Process(target=mask,)
    p3 = multiprocessing.Process(target=alarm,)

    p1.start()
    p2.start()
    p3.start()
    

Solution

  • Have a look at the Python docs on multiprocessing, especially the parts about exchanging objects between processes and sharing state between processes.

    If all you want to do is signal your main process when some conditions occur, an Event object should probably be enough. If you want to exchange more complex data between the processes, a Queue would be better suited.

    With the Event objects your code could look roughly like this:

    import multiprocessing
    from random import random
    import time
    
    
    def mask(event):
        while True:
            if random() < 0.1:
                event.set()
            time.sleep(1)
    
    
    def cough(event):
        while True:
            if random() < 0.2:
                event.set()
            time.sleep(1)
    
    
    def alarm(events):
        while True:
            for i, event in enumerate(events, start=1):
                # wait for up to a second for the event to be set by the other process
                # and then wait for the next event
                if event.wait(1):
                    print('Error ' + str(i))
                    event.clear()
    
    
    def main():
        e1 = multiprocessing.Event()
        p1 = multiprocessing.Process(target=mask, args=(e1,))
        p1.start()
    
        e2 = multiprocessing.Event()
        p2 = multiprocessing.Process(target=cough, args=(e2,))
        p2.start()
    
        alarm([e1, e2])
    
    
    if __name__ == '__main__':
        main()