Skip to main content

A Python library providing token-based locking for efficient coordination of asynchronous tasks in asyncio.

Project description

Asyncio Tokenized Lock

codecov PyPI PyPI - Python Version

Asyncio Tokenized Lock is a Python library that provides a token-based locking mechanism for managing asynchronous locks in an asyncio environment. It introduces two main classes, LockManager and TokenizedLock, to facilitate the coordination of asynchronous tasks with associated tokens.

Features

  • Tokenized Locking: Locks are associated with tokens, allowing for fine-grained control over asynchronous operations.
  • Asynchronous Support: Built on asyncio, enabling efficient coordination of asynchronous tasks.
  • Context Manager Interface: TokenizedLock can be used as an asynchronous context manager for clean and concise lock management.
  • Timeout Support: The library supports timeouts for lock acquisition.

Installation

pip install asyncio-tokenized-lock

Usage (Examples)

Basic Usage

from asyncio_tokenized_lock.lock import LockManager, TokenizedLock

manager = LockManager[str]()
lock = manager.register("example_token")

# Acquire and release the lock
async with lock:
    # Perform operations while holding the lock
    pass

Timeout

Context Manager

from asyncio_tokenized_lock.lock import LockManager, TokenizedLock

manager = LockManager[str]()
token = "example_token"
lock = manager.register(token)
lock.ctx_timeout = 1.0  # Set the timeout to 1 second
try:
    # Acquire the lock with a timeout using context manager
    async with lock:
        # Perform operations while holding the lock
        pass
except asyncio.TimeoutError:
    ...

Inline

try:
    await lock.acquire(timeout=1.0)
    # Perform operations while holding the lock
except asyncio.TimeoutError:
    print("Lock acquisition timed out")

Queue Concurrency

import asyncio
import uuid
import logging
from asyncio_tokenized_lock.lock import LockManager, TokenizedLock

log = logging.getLogger("my-module")

async def consume_queue_safely(concurrency: int = 5, queue_size: int = 100):
    manager = LockManager[str]()
    queue = asyncio.Queue()
    put_tasks = [
        asyncio.ensure_future(queue.put(item=uuid.uuid4()))
        for _ in range(queue_size)
    ]

    async def safe_consume(queue: asyncio.Queue):
        while not queue.empty():
            item = await queue.get()
            lock = manager.register(item)

            if lock.locked:
                continue

            async with lock:
                # Perform operations with the locked item
                yield item

    # Worker class to consume from the queue safely
    @dataclass
    class Worker:
        id: str
        queue: asyncio.Queue

        async def consume(self):
            while True:
                async for item in safe_consume(self.queue):
                    # Perform operations with the item
                    log.info(f"[WORKER-{self.id}] Item {item} processed")
                break

    workers = [Worker(id=str(i), queue=queue) for i in range(concurrency)]
    consume_tasks = [asyncio.ensure_future(w.consume()) for w in workers]

    # Wait for tasks to complete
    await asyncio.wait(put_tasks)
    await asyncio.wait(consume_tasks)

Testing

poetry run pytest

Run the provided test suite to ensure the correct behavior of the LockManager and TokenizedLock classes in different scenarios.

Contributing

Contributions are welcome! Feel free to open issues, submit pull requests, or suggest improvements.

License

This library is licensed under the MIT License - see the 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

asyncio_tokenized_lock-0.1.3.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

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

asyncio_tokenized_lock-0.1.3-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file asyncio_tokenized_lock-0.1.3.tar.gz.

File metadata

  • Download URL: asyncio_tokenized_lock-0.1.3.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.10.13 Linux/6.2.0-1016-azure

File hashes

Hashes for asyncio_tokenized_lock-0.1.3.tar.gz
Algorithm Hash digest
SHA256 7649cbf304551dafa5069b5a172995901ec439de1479d3842c7a316c87f97b75
MD5 88ae8925573fc31804a405428a413c01
BLAKE2b-256 eca6dff2244b8aa82101480833eaa066420e7ddcd06c70b95bd388541e668799

See more details on using hashes here.

File details

Details for the file asyncio_tokenized_lock-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for asyncio_tokenized_lock-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 a3c36a6a60f73bcc54282c39b44e4a4b12348693e3a03253281bc70362494265
MD5 10254121a9764383db732876b4e7a869
BLAKE2b-256 a00cd4cb17e3560863d3e1a5abe20b6eef4c2f58b3cc82d73e9737b80f25cd95

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