Skip to main content

Resource Semaphore

License Python Coverage

Resource Semaphore is a typed, high-level synchronization library for managing multiple constrained resources within a single process. It applies backpressure to prevent resource exhaustion.

Standard semaphores guard a single counter of "slots." resource-semaphore extends this to multiple, heterogeneous resources: such as CPU cores, available RAM, disk I/O bandwidth, or worker slots: with a single, atomic acquire/release operation. When capacity is exhausted, callers block until resources become available.

Installation

pip install resource-semaphore

Quick Start

import asyncio
from resource_semaphore import AsyncResourceSemaphore

semaphore = AsyncResourceSemaphore(resources={"db_conn": 2, "ram_mb": 4096})


async def process(data_size_mb: float):
    async with semaphore.claim({"db_conn": 1, "ram_mb": data_size_mb}):
        await do_work()


async def main():
    # Three tasks compete for 2 DB connections: one will wait automatically
    await asyncio.gather(
        process(1024),
        process(1024),
        process(1024),
    )

Features

  • Multi-resource: manage DB connection, RAM, workers, or any named resource in a single semaphore
  • Sync + Async: ResourceSemaphore for threads, AsyncResourceSemaphore for asyncio
  • Infinite Bypass Fairness: Avoids starvation by prioritizing older requests, while automatically allowing smaller queued requests to safely bypass blocked heavy tasks, completely eliminating head-of-line blocking deadlocks.
  • Greedy Variants: GreedyResourceSemaphore and AsyncGreedyResourceSemaphore skip queueing entirely for maximum utilization in non-starving pipelines.
  • High Performance: Built on a shared template base class architecture, heavily optimizing acquisition loops by stripping unnecessary overhead from greedy implementations.
  • Timeouts: abort waits gracefully using timeout arguments
  • Safe Releases: opaque Ticket objects prevent corrupted state from incorrect releases
  • Typed: generic over resource key types via Literal for compile-time safety
  • No-op variants: NoopResourceSemaphore and AsyncNoopResourceSemaphore for tests
  • Graceful shutdown: shutdown() wakes all blocked callers with a SemaphoreError
  • Zero dependencies (Core): pure Python, nothing to install beyond the standard library
  • System Utilities: dynamic initialization via resource-semaphore[utils] for fetching CPU/RAM limits

Documentation

For a comprehensive guide on core concepts, initialization, and API usage (including both synchronous and asynchronous context managers), please refer to our documentation:

Examples

We provide runnable scripts demonstrating real-world usage scenarios:

Roadmap

To see what features are planned for future releases and what has already been accomplished, check out our TODO.md tracker.

Download files

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

Source Distribution

resource_semaphore-1.3.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

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

resource_semaphore-1.3.0-py3-none-any.whl (15.0 kB view details)

Uploaded Python 3

File details

Details for the file resource_semaphore-1.3.0.tar.gz.

File metadata

  • Download URL: resource_semaphore-1.3.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for resource_semaphore-1.3.0.tar.gz
Algorithm Hash digest
SHA256 38681f29a256cffc5dbbb8409f4a70f4900557d61300347f3f3a62c39153778d
MD5 bc0552eaa10a381ee03729815ed04e95
BLAKE2b-256 8344655a1361ec277664d4c0985ae9f28732de56a9ca8854d96fb744ece5aaed

See more details on using hashes here.

File details

Details for the file resource_semaphore-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: resource_semaphore-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 15.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for resource_semaphore-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 20f272d886a1e7d6eae9766359a1be0a4e69bcd2c6d539b101d9d83fc3496311
MD5 d7efe5abffdb001e41f0ba568599f53b
BLAKE2b-256 e5b660d464bfd4c58df6b8d125ab681c53b957e2b72fb31689ca751fc68275fc

See more details on using hashes here.

Release history Release notifications | RSS feed

1.3.1

2 files

This release

1.3.0 This release

2 files

1.1.0

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page