Search code examples
pythonmultiprocessingsigpipe

Run two functions at the same time in Python


This is a simple code for multi threading in python.

p1 = multiprocessing.Process(target=f1, args=('f1')) 
p2 = multiprocessing.Process(target=f2, args=('f2')) 

p1.start() 
# starting process 2 
p2.start() 

# wait until process 1 is finished 
p1.join() 
# wait until process 2 is finished 
p2.join()

But after running the code I'm getting the following error:

BrokenPipeError: [Errno 32] Broken pipe

I searched SO and other sites and the common answer was to include the following snippet:

from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)

But when I run this, I'm getting the following error:

ImportError: cannot import name 'SIGPIPE' from 'signal' (C:\Users\u65988\AppData\Local\Continuum\anaconda3\lib\signal.py)

I tried checking all solutions, but none of them is working out! Please help me out on this!

For reference both functions:

def f1 (string):
          print(string)

def f2 (string):
          print(string)

Solution

  • In your main.py/script you wish to run, you have to write

    if __name__ == "__main__":
    
        start_process_1()
    
        start_process_2()
    
    
        join_process_1()
    
        join_process_2()
    

    This is an error specific to Windows platforms, and is solved accordingly if the function calls are wrapped/put inside the if__name__ == "__main__".