{"id":6916,"library":"threaded","title":"Threaded","description":"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.","status":"active","version":"4.2.0","language":"en","source_language":"en","source_url":"https://github.com/python-useful-helpers/threaded","tags":["concurrency","threading","thread-pool","asyncio","decorators"],"install":[{"cmd":"pip install threaded","lang":"bash","label":"Install stable version"}],"dependencies":[],"imports":[{"symbol":"ThreadPooled","correct":"from threaded import ThreadPooled"},{"note":"Alias for ThreadPooled","symbol":"threadpooled","correct":"from threaded import threadpooled"},{"symbol":"Threaded","correct":"from threaded import Threaded"},{"note":"Alias for Threaded","symbol":"threaded","correct":"from threaded import threaded"},{"symbol":"AsyncIOTask","correct":"from threaded import AsyncIOTask"},{"note":"Alias for AsyncIOTask","symbol":"asynciotask","correct":"from threaded import asynciotask"}],"quickstart":{"code":"import time\nimport concurrent.futures\nfrom threaded import ThreadPooled\n\n# Configure the thread pool (optional, defaults to CPU_COUNT * 5 workers)\nThreadPooled.configure(max_workers=3)\n\n@ThreadPooled\ndef process_item(item_id):\n    print(f\"Processing item {item_id} in a thread...\")\n    time.sleep(1) # Simulate I/O-bound work\n    return f\"Item {item_id} processed.\"\n\nif __name__ == \"__main__\":\n    print(\"Submitting tasks to the thread pool...\")\n    futures = [process_item(i) for i in range(5)]\n\n    # Wait for all tasks to complete and retrieve results\n    for future in concurrent.futures.as_completed(futures):\n        try:\n            result = future.result()\n            print(f\"Result: {result}\")\n        except Exception as exc:\n            print(f'Task generated an exception: {exc}')\n\n    print(\"All tasks submitted and results collected.\")\n    # It's crucial to explicitly shut down the thread pool for graceful exit\n    ThreadPooled.shutdown()\n    print(\"Thread pool shut down.\")","lang":"python","description":"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."},"warnings":[{"fix":"Understand the GIL's implications. For true CPU-bound parallelism, use `multiprocessing` or investigate GIL-free Python builds (Python 3.13+).","message":"Python's Global Interpreter Lock (GIL) means that standard CPython threads cannot execute CPU-bound tasks in parallel across multiple cores. This library, by using `threading` and `concurrent.futures.ThreadPoolExecutor`, primarily benefits I/O-bound tasks where threads can yield the GIL while waiting. For CPU-bound parallelism, consider `multiprocessing`.","severity":"gotcha","affected_versions":"All versions on GIL-enabled CPython"},{"fix":"Ensure `ThreadPooled.shutdown()` is called, typically at the end of your main execution path or within a `finally` block to guarantee execution. If used as part of a longer-running service, manage its lifecycle carefully.","message":"When using `ThreadPooled` (which leverages `ThreadPoolExecutor`), it's important to explicitly call `ThreadPooled.shutdown()` when your application is exiting or when the pool is no longer needed. Failure to do so can lead to resource leaks, prevent the program from exiting cleanly, or cause issues during application shutdown.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Minimize shared mutable state. When unavoidable, use explicit synchronization primitives like `threading.Lock`, `threading.Semaphore`, or thread-safe data structures from the `queue` module to manage access to shared resources.","message":"Like any concurrency mechanism, using `threaded` with shared mutable state (e.g., global variables, class attributes, shared objects) can lead to race conditions if access is not properly synchronized. This can result in unpredictable behavior or corrupted data.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z","problems":[]}