Threaded

4.2.0 · active · verified Wed Apr 15

Threaded is a Python library providing decorators for easily wrapping functions to run in `concurrent.futures.ThreadPoolExecutor`, `threading.Thread`, or `asyncio.Task`. It aims to reduce boilerplate code associated with managing concurrent operations. The library is actively maintained, with its latest version being 4.2.0, and has a consistent release cadence.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `ThreadPooled` decorator to run functions in a `ThreadPoolExecutor`. It configures a pool with 3 workers, submits 5 tasks, waits for their completion, and then explicitly shuts down the pool.

import time
import concurrent.futures
from threaded import ThreadPooled

# Configure the thread pool (optional, defaults to CPU_COUNT * 5 workers)
ThreadPooled.configure(max_workers=3)

@ThreadPooled
def process_item(item_id):
    print(f"Processing item {item_id} in a thread...")
    time.sleep(1) # Simulate I/O-bound work
    return f"Item {item_id} processed."

if __name__ == "__main__":
    print("Submitting tasks to the thread pool...")
    futures = [process_item(i) for i in range(5)]

    # Wait for all tasks to complete and retrieve results
    for future in concurrent.futures.as_completed(futures):
        try:
            result = future.result()
            print(f"Result: {result}")
        except Exception as exc:
            print(f'Task generated an exception: {exc}')

    print("All tasks submitted and results collected.")
    # It's crucial to explicitly shut down the thread pool for graceful exit
    ThreadPooled.shutdown()
    print("Thread pool shut down.")

view raw JSON →