Stephen Flegg
Stephen Flegg

Reputation: 41

Why does my python script continue while if __name__==__main__ runs?

Below is a simplified version of a problem I'm facing. When I run my code, example below, why does the script run code below the if _name__==__main_ section while the function which sits underneath the if statement is still running? I thought the p_1.join() command should block the script from continuing until the separate process has finished. In the output below I'm expecting the word "Finished" to only be printed when all of the script has concluded - but instead it is being printed second and then last.

In the past I have used poolexecutor for similar problems; but in this project I need to start each process individually so that I can assigned separate independent functions to each process.

import time
from multiprocessing import Process, Queue

def a(x,q):
    time.sleep(3)
    q.put(x*x)

q=Queue()
def main():
    print("Main Function Starts")
    p_1 = Process(target=a, args=(5,q))
    p_1.start()
    p_1.join()
    b= q.get()
    print(b)
    print("Main Function Ends")

if __name__ == '__main__':        
       main()

print("Finished")

**Output:**
Main Function Starts
Finished
25
Main Function Ends
Finished

Upvotes: 3

Views: 872

Answers (2)

cuspymd
cuspymd

Reputation: 1088

How do you run your script? When I ran your script on command line, 'Finished' was printed once like below.

$ python test.py

Main Function Starts
25
Main Function Ends
Finished

Upvotes: 0

user2357112
user2357112

Reputation: 281177

You were supposed to put that code in the if __name__ == '__main__' guard. Preventing this kind of thing is the whole point of if __name__ == '__main__'.

You're on Windows. When you start p_1, multiprocessing launches a separate Python process, and one of the first things that process does is import your file as a module. When it does that, the module's __name__ isn't '__main__', so anything inside the if __name__ == '__main__' guard doesn't run, but print("Finished") is outside the guard.

Your program isn't somehow continuing past main() while main() is still running. The worker process is performing the unwanted print.

Upvotes: 4

Related Questions