The multiprocessing module
suggest changeimport multiprocessing
def countdown(count):
while count > 0:
print("Count value", count)
count -= 1
return
if __name__ == "__main__":
p1 = multiprocessing.Process(target=countdown, args=(10,))
p1.start()
p2 = multiprocessing.Process(target=countdown, args=(20,))
p2.start()
p1.join()
p2.join()
Here, each function is executed in a new process. Each process has its own GIL, so Python code can run in parallel on multiple cores.
The Process.start method launches this new process and runs the function passed in the target argument with the arguments args. The Process.join method waits for the end of the execution of processes p1 and p2.
The new processes are launched differently depending on the version of Python and the platform on which the code is running, for example:
- Windows uses
spawnto create the new process. - Before Python 3.4, POSIX systems created the new process with
forkonly.
Note that fork does not follow the POSIX rule for fork in a multithreaded program and can lead to unexpected behavior, especially when interacting with other multiprocessing libraries.
- From Python 3.4, call
multiprocessing.set_start_methodat the beginning of the program to choosefork,forkserver, orspawn.forkserverexists on some POSIX platforms.forkserverandspawnare slower thanforkbut avoid some unexpected behavior. As of Python 3.14,forkis not the default on any platform: supporting POSIX platforms default toforkserver, and Windows and macOS default tospawn.
POSIX fork usage:
After a fork in a multithreaded program, the child can safely call only async-signal-safe functions until such time as it calls execve.
(see)
Using fork, a new process starts with the same state for every current mutex, but only the MainThread is launched. This is unsafe and can lead to race conditions, for example:
- If you use a
LockinMainThreadand pass it to another thread which is supposed to lock it at some point, and theforkhappens while that lock is held, the new process starts with the lock already locked. It will never be released, because the second thread does not exist in the new process.
multiprocessing repairs its own locks after a fork, but a lock held by another thread, including one owned by another library, stays locked in the child and can deadlock (for instance with NumPy or Accelerate on macOS).