To implement parallel execution in Python, you can use the multiprocessing module. Here’s a simple example that demonstrates how to run tasks in parallel:
import multiprocessing
import time
def worker(task_id):
print(f"Task {task_id} is starting.")
time.sleep(2) # Simulate a time-consuming task
print(f"Task {task_id} is completed.")
if __name__ == "__main__":
tasks = [1, 2, 3, 4, 5] # List of tasks
processes = []
# Create a process for each task
for task_id in tasks:
process = multiprocessing.Process(target=worker, args=(task_id,))
processes.append(process)
process.start() # Start the process
# Wait for all processes to complete
for process in processes:
process.join()
print("All tasks are completed.")
Explanation:
- Importing the Module: The
multiprocessingmodule is imported to handle parallel execution. - Defining the Worker Function: The
workerfunction simulates a task that takes time to complete. - Creating Processes: For each task, a new process is created and started.
- Joining Processes: The main program waits for all processes to finish using
join().
This example will run five tasks in parallel, each simulating a time-consuming operation. You can adjust the number of tasks and the workload as needed.
