Skip to main content

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:

  1. Update version in pyproject.toml.
  2. Update __version__ in betapool/__init__.py.
  3. Add release notes to CHANGELOG.md.
  4. Create and push a matching git tag, for example v1.0.2.
  5. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

betapool-1.0.2.tar.gz (24.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

betapool-1.0.2-py3-none-any.whl (17.6 kB view details)

Uploaded Python 3

File details

Details for the file betapool-1.0.2.tar.gz.

File metadata

  • Download URL: betapool-1.0.2.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

Hashes for betapool-1.0.2.tar.gz
Algorithm Hash digest
SHA256 4d02ac444536eb9aaf1fea5559514d16713727141c890a4eb28ee1a8382f1343
MD5 b4963af9712eb7d9d777aba0728d34e3
BLAKE2b-256 a9349ff0064af0727365815eb1c8494db9eaefa75e64e0da989ce066e5bb4158

See more details on using hashes here.

File details

Details for the file betapool-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: betapool-1.0.2-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

Hashes for betapool-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 adcee6579eccb71be76970c8eb5c66c15c58783eccba84011d68b89c83062c8e
MD5 1d125b09ac505153e9978ae3e62b13e6
BLAKE2b-256 88e1b5be364ae5dc31de001fa77eae363b1c4c5c1b4f7c3bd362af8ce92eb367

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page