Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiprocess code in python fails to execute on windows side

I have written a very basic code to test multiprocess in python.
When i try to run the code on my windows machine, it does not run while it works fine on linux machine.
Below is the code and the error that it throws.

from multiprocessing import Process
import os
import time

# creating a list to store all the processes that will be created
processes = []

# Get count of CPU Cores
cores = os.cpu_count()
def square(n): #just creating a random program for demostration
    for i in range (n):
        print(i)
        i*i
        time.sleep(0.1)

# create a process.
for i in range(cores):
    p = Process(target=square,args=(100,)) 
    processes.append(p)

#statrting all the processes
for proc in processes:
    proc.start()

# join process
for proc in processes:
    proc.join()

print("All processes are done")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Most Process executions (Not Threads) on Python will start a new instance importing itself. This means your global code will be executed every time the instance is doing the import. (This only applies to the spawn start method)

In order to avoid these issues, you have to move your code into the if __name__ == "__main__": function in order for the Process to create a new instance correctly.

You fix it like so:

from multiprocessing import Process
import os
import time

def square(n): #just creating a random program for demostration
    for i in range (n):
        print(i)
        i*i
        time.sleep(0.1)

if __name__ == "__main__":
    # Get count of CPU Cores
    cores = os.cpu_count()
    # creating a list to store all the processes that will be created
    processes = []
    # create a process.
    for i in range(cores):
        p = Process(target=square,args=(100,)) 
        processes.append(p)
    #statrting all the processes
    for proc in processes:
        proc.start()
    # join process
    for proc in processes:
        proc.join()
    print("All processes are done")

Result:

1
0
0
1
1
0
2
0
0
1
1
1
2
... Truncated
All processes are done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading