172. Using ThreadPoolExecutor for Parallelism

Snippet 1: Basic Example with ThreadPoolExecutor

Copy

from concurrent.futures import ThreadPoolExecutor

def print_number(number):
    print(f"Number: {number}")

with ThreadPoolExecutor(max_workers=3) as executor:
    executor.map(print_number, range(5))

Snippet 2: Parallel File Reading

Copy

from concurrent.futures import ThreadPoolExecutor

def read_file(filename):
    with open(filename, 'r') as f:
        return f.read()

filenames = ["file1.txt", "file2.txt", "file3.txt"]
with ThreadPoolExecutor() as executor:
    results = list(executor.map(read_file, filenames))

for i, content in enumerate(results):
    print(f"Content of {filenames[i]}:\n{content}")

Snippet 3: Fetching Web Pages Concurrently

Copy


Snippet 4: Calculating Squares Concurrently

Copy


Snippet 5: Running Functions with submit

Copy


Snippet 6: Parallel Sorting of Multiple Lists

Copy


Snippet 7: Performing Delayed Tasks

Copy


Snippet 8: Factorial Calculation in Parallel

Copy


Snippet 9: Writing to Multiple Files

Copy


Snippet 10: Handling Exceptions in ThreadPoolExecutor

Copy


Last updated