What does start and join mean in multiprocessing in Python


In Python’s multiprocessing module, the start() and join() methods are used to control the execution of a Process object.

start()

The start() method is used to start a new process, which begins running the target function specified during the Process object’s creation. When you call start() on a Process object, the following happens:

  1. A new process is created by the operating system.
  2. The new process begins executing the target function, along with any arguments passed to it, in a separate environment with its own memory space.
from multiprocessing import Process

def my_function(x):
print(f'Processing {x}')

process = Process(target=my_function, args=(42,))
process.start() # This starts the execution of my_function in a new process

join()

The join() method is used to block the main process (i.e., the script that initiated the new process) until the target process completes its execution. This is useful for synchronizing processes and ensuring that the main process waits for all child processes to finish before continuing.

When you call join() on a Process object, the following happens:

  1. The main process is blocked and waits for the target process to finish its execution.
  2. Once the target process is completed, the join() method returns, and the main process continues executing.
from multiprocessing import Process

def my_function(x):
print(f'Processing {x}')

process = Process(target=my_function, args=(42,))
process.start() # Start the execution of my_function in a new process
process.join() # Wait for the new process to complete before continuing
print("Process completed")

In this example, the join() method ensures that the “Process completed” message is printed only after the my_function has finished executing in the new process.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC