Use the built-in multiprocessing module.
import multiprocessing
Quick links:
The core class is multiprocessing.Process.
Define the target function: This is the code that the new process will run.
def my_process_task(argument1, argument2):
# Code to be executed in the new process
print(f"Process received: {argument1}, {argument2}")
# ... perform task ...
Create a Process object:
process = multiprocessing.Process(target=my_process_task, args=(value1, value2))
target: The function to be executed in the new process.args: A tuple of positional arguments to pass to the target function. Use a comma after the single item if passing only one argument (e.g., args=(value1,)).kwargs: (Optional) A dictionary of keyword arguments to pass to the target function.Start the process:
process.start()
Wait for the process to complete:
process.join()
join() method is called terminates.import multiprocessing
import time
def worker_function(name):
print(f"Worker process {name} starting...")
time.sleep(2) # Simulate doing some CPU-bound work
print(f"Worker process {name} finishing.")
if __name__ == "__main__":
# Create two processes
p1 = multiprocessing.Process(target=worker_function, args=("Alpha",))
p2 = multiprocessing.Process(target=worker_function, args=("Beta",))
# Start the processes
p1.start()
p2.start()
# Wait for both processes to complete
p1.join()
p2.join()
print("All processes finished.")
if __name__ == "__main__": block is crucial on some operating systems (like Windows) to prevent processes from recursively spawning new processes when the module is imported by the new process.