Reputation: 121
I'm trying to get the hang of Python multiprocessing but my tests so far show sequential running instead of parallelism.
I tried this simple code:
multiprocessing.py:
import multiprocessing
import os
def proc1():
os.system('python proc1.py')
def proc2():
os.system('python proc2.py')
if __name__ == "__main__":
p1 = multiprocessing.Process(target=proc1())
p2 = multiprocessing.Process(target=proc2())
p1.start()
p2.start()
proc1.py:
import time
for i in range(0,5):
print('process 1: ', i)
time.sleep(0.5)
proc2.py:
import time
for i in range(0,5):
print('process 2: ', i)
time.sleep(0.5)
My understanding is that this should run parallel on different CPUs, however, the console output is always this:
process 1: 0
process 1: 1
process 1: 2
process 1: 3
process 1: 4
process 2: 0
process 2: 1
process 2: 2
process 2: 3
process 2: 4
Process finished with exit code 0
I think the two process outputs should be mixed and in varying order, depending on which core is 'faster'. Is this a limitation of Pycharm? Or am I doing something wrong?
Upvotes: 0
Views: 152
Reputation: 460
It's a simple error in syntax. By doing
p1 = multiprocessing.Process(target=proc1())
you are saying that the target should be the output from proc1. What you want is
p1 = multiprocessing.Process(target=proc1)
That way the target is the function proc1
Upvotes: 2