How do I chunk work and process in parallel?

In this example, we will demonstrate how to use Python's concurrent.futures library to chunk work and process it in parallel. This can greatly improve the efficiency of your programs, especially when dealing with I/O-bound tasks.

Keywords: parallel processing, concurrent.futures, Python, threads, processes, I/O-bound tasks
Description: This tutorial covers how to divide tasks into chunks and process them concurrently using Python's built-in libraries, enhancing productivity and reducing execution time.
import concurrent.futures
import time

# Simulate a time-consuming task
def task(n):
    time.sleep(1)  # Simulate a delay
    return f'Task {n} completed'

# Chunking and processing in parallel
def main():
    tasks = range(10)  # Create a list of tasks
    with concurrent.futures.ThreadPoolExecutor() as executor:
        results = list(executor.map(task, tasks))
    for result in results:
        print(result)

if __name__ == "__main__":
    main()
        

Keywords: parallel processing concurrent.futures Python threads processes I/O-bound tasks