# Multiprocessing module should be installed by default import multiprocessing as mp # Other imports import time # Verify that we have multiple CPU cores print(f"This CPU has {mp.cpu_count()} cores.") # Define our example function def simulate_long_task(task_data): """tuple(str, int) -> None Prints the task name and sleeps for the task_time.""" # Unpack the task data task_name = task_data[0] task_time = task_data[1] # Simulate a long task print(f"Task {task_name} runs for {task_time} seconds.") time.sleep(task_time) print(f"Task {task_name} complete!") # Demo the function simulate_long_task(("Test", 2)) # Define an example set of tasks and times task_list = [ ("A", 6), ("B", 2), ("C", 4) ] # Run this in a loop for item in task_list: simulate_long_task(item) # Use map function without multiprocessing print("\nBeginning without multiprocessing...") out2 = list(map(simulate_long_task, task_list)) print("Beginning with multiprocessing...") # Create our multiprocessing handler # This will automatically assign tasks to each CPU core p = mp.Pool() # Can specify number of cores to use # Send the functions and list of inputs to the handler out = p.map(simulate_long_task, task_list)