I'm new into multiprocessing
in Python (2.7).
I try to run the following piece of code:
from time import sleep
from multiprocessing import Process
import multiprocessing
def func(x):
print("start %s"%(x))
sleep(x)
print("end %s"%(x))
return
if __name__ == '__main__':
Process(target=func(10)).start()
Process(target=func(1)).start()
This return something as :
start 10
end 10
start 1
end 1
While start 1
and end 1
should a priori appear before end 10
.
I would appreciate help to understand what I might be missing here.
Using Willem Van Onsem answer:
You can use a lot of Process more to see when they're called and when they finish. Use other Process calls to see how they work.
You write:
This means that the
Process
never is givenfunc
, it is given the result offunc(10)
since Python first evaluates the arguments left-to-right, and then passes the result of these evaluations to the outer function (here theProcess(..)
call).In order to let the subprocess evaluate the function, you should write it like:
Now you pass a reference to the
func
function, and you provide a tuple of argumentsargs
with which the sub process is going to call the function. The subprocess will then callfunc(10)
itself (and another subprocess will almost concurrently do the same withfunc(1)
).When creating a
Process
,target
should be function name only without arguments or parantheses and then you addargs=(your args)
. For example: