0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.