Adaptive Thread Pool for GIL-Aware Concurrency Control in Python
Project description
BetaPool:
A Python library implementing the Metric-Driven Adaptive Thread Pool for mitigating GIL bottlenecks in mixed I/O and CPU workloads.
Author: Mridankan Mandal
License: MIT
Python: 3.8+
Overview:
Standard thread pool implementations fail to detect GIL-specific contention in Python, leading to concurrency thrashing where increasing thread count paradoxically degrades throughput. BetaPool solves this by implementing a GIL Safety Veto mechanism using the Blocking Ratio (beta) metric to automatically maintain optimal concurrency levels.
Why BetaPool:
Research demonstrates that naive thread scaling causes significant performance degradation:
| Configuration | Peak Throughput | Degradation at High Threads |
|---|---|---|
| Single-core | 37,437 TPS at 32 threads | 32.2% loss at 2048 threads |
| Quad-core | 68,742 TPS at 64 threads | 33.3% loss at 2048 threads |
| BetaPool | 36,142 TPS | 96.5% of optimal (automatic) |
BetaPool achieves near-optimal performance without manual tuning by detecting when thread scaling would cause GIL contention.
Installation:
From PyPI:
pip install betapool
From source:
git clone https://github.com/RedZapdos123/BetaPool.git
cd BetaPool
pip install -e .
With optional dependencies:
pip install -e ".[dev]" # Development tools.
pip install -e ".[numpy]" # NumPy workload generators.
pip install -e ".[all]" # All dependencies.
Quick Start:
from betapool import AdaptiveThreadPoolExecutor
# Drop-in replacement for ThreadPoolExecutor.
with AdaptiveThreadPoolExecutor(min_workers=4, max_workers=64) as executor:
futures = [executor.submit(my_task, arg) for arg in args]
results = [f.result() for f in futures]
# Monitor adaptive behavior.
metrics = executor.get_metrics()
print(f"Current threads: {metrics['current_threads']}")
print(f"Blocking ratio: {metrics['avg_blocking_ratio']:.2f}")
The Blocking Ratio:
The core algorithm uses the Blocking Ratio metric:
beta = 1 - (cpu_time / wall_time)
- beta near 1.0: Thread is mostly waiting (I/O-bound). Safe to add threads.
- beta near 0.0: Thread is mostly computing (CPU-bound). Adding threads causes GIL contention.
The GIL Safety Veto:
When beta falls below the danger threshold (default 0.3), the controller vetoes thread pool expansion:
if beta > threshold: # I/O-bound work.
scale_up() # Safe to add threads.
else:
hold() # VETO: Prevents GIL thrashing.
This mechanism prevents the 32% throughput loss observed with naive thread scaling.
API Reference:
AdaptiveThreadPoolExecutor:
from betapool import AdaptiveThreadPoolExecutor, ControllerConfig
config = ControllerConfig(
monitor_interval_sec=0.5, # Metric check interval.
beta_high_threshold=0.7, # Scale up threshold.
beta_low_threshold=0.3, # GIL danger zone.
scale_up_step=2, # Threads to add.
scale_down_step=1, # Threads to remove.
)
with AdaptiveThreadPoolExecutor(
min_workers=4,
max_workers=64,
config=config
) as executor:
future = executor.submit(task_function, arg1, arg2)
result = future.result()
Methods:
submit(fn, *args, **kwargs) -> Future: Submit a task for execution.map(fn, *iterables, timeout=None) -> Iterator: Map function over iterables.get_current_thread_count() -> int: Get current active thread count.get_metrics() -> Dict: Get current metrics summary.shutdown(wait=True): Shutdown the executor.
Testing:
python -m pip install -e ".[dev]"
python -m pytest betapool/tests/ -v
Release:
BetaPool uses semantic versions. Before publishing a release:
- Update
versioninpyproject.toml. - Update
__version__inbetapool/__init__.py. - Add release notes to
CHANGELOG.md. - Create and push a matching git tag, for example
v1.0.1. - Publish a GitHub Release from that tag.
The Publish to PyPI GitHub Actions workflow builds the package and uploads it to PyPI when a GitHub Release is published. Add the PyPI API token to the GitHub repository secret named PYPI_API_TOKEN; never commit it to the repository.
Manual package validation:
python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
Research Paper:
Read the full paper: Mitigating GIL Bottlenecks in Edge AI Systems (arXiv:2601.10582)
Citation:
@article{mandal2026gilscheduler,
title={Mitigating GIL Bottlenecks in Edge AI Systems: A Metric-Driven Adaptive Thread Pool},
author={Mandal, Mridankan},
journal={arXiv preprint arXiv:2601.10582},
year={2026},
url={https://arxiv.org/abs/2601.10582}
}
License:
MIT License - see LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file betapool-1.0.1.tar.gz.
File metadata
- Download URL: betapool-1.0.1.tar.gz
- Upload date:
- Size: 24.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c29316358077ee7b44fd70b9e4acdfcead4cf578c6a44a8f11afedebff3eddb4
|
|
| MD5 |
b10cbc1117c9531f8451772e9430d329
|
|
| BLAKE2b-256 |
5e9d8587e5478ce276dbb73f5a43a3fee6a4f44d78ef25e54afb68c1614a311b
|
File details
Details for the file betapool-1.0.1-py3-none-any.whl.
File metadata
- Download URL: betapool-1.0.1-py3-none-any.whl
- Upload date:
- Size: 17.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
19797d64be7619ce78162d330566cf5adc0be3eb21f45f566793320d704e8f38
|
|
| MD5 |
5df477118726d6490b05f06df8fb12e5
|
|
| BLAKE2b-256 |
3a5237a7403ba315348df738290f9a846eefaf6d6cf5f3964abe8c6eb6f654f5
|