Processes are not executing parallel when while loop is used inside a process in python

Viewed 26

I am trying to run following code structure in python using multiprocessing. I am using while loop inside the process target so that the process is independently executing code periodically.However, it seems that processes are not getting executed parallel, rather serial execution happening. When i remove the while loop then processes works fine. I tried to search for similar questions, and found that there was no concrete answer

import multiprocessing
import datetime, time


def f1():
    while True:
        print('F1 Cyclic : ', datetime.datetime.now())
        time.sleep(1)
        
        
def f2():
    while True:
        print('F2 Cyclic : ', datetime.datetime.now())
        time.sleep(2)
        

print('Starting main')
       
f1Process = multiprocessing.Process(target=f1())

f2Process = multiprocessing.Process(target=f2())

f1Process.daemon = False
f2Process.daemon = False

f1Process.start()
f2Process.start()   

# f1Process.join()
# f2Process.join()     

print('Ending main')

My result looks like this

Starting main

F1 Cyclic : 2022-06-20 16:08:14.912327

F1 Cyclic : 2022-06-20 16:08:15.928739

F1 Cyclic : 2022-06-20 16:08:16.935977

F1 Cyclic : 2022-06-20 16:08:17.946611

F1 Cyclic : 2022-06-20 16:08:18.955279

F1 Cyclic : 2022-06-20 16:08:19.959641

F1 Cyclic : 2022-06-20 16:08:20.960894

F1 Cyclic : 2022-06-20 16:08:21.971137

1 Answers

The issue arises because of these 2 lines, setting the target as f1()/f2() is executing the function in that line therefore, it gets stuck in infinite while loop(when f1() is called):

f1Process = multiprocessing.Process(target=f1())
f2Process = multiprocessing.Process(target=f2())

Assign target as below to fix the issue:

f1Process = multiprocessing.Process(target=f1)
f2Process = multiprocessing.Process(target=f2)

The correct working code should be:

import multiprocessing
import datetime, time


def f1():
    while True:
        print('F1 Cyclic : ', datetime.datetime.now())
        time.sleep(1)


def f2():
    while True:
        print('F2 Cyclic : ', datetime.datetime.now())
        time.sleep(2)

if __name__ == '__main__':
    print('Starting main')

    f1Process = multiprocessing.Process(target=f1)
    f2Process = multiprocessing.Process(target=f2)

    f1Process.daemon = False
    f2Process.daemon = False

    f1Process.start()
    f2Process.start()

    # f1Process.join()
    # f2Process.join()     

    print('Ending main')
Related