Skip to content

Adding new synchronous methods to asyncio #123117

@Alpha-Qian

Description

@Alpha-Qian

Feature or enhancement

Proposal:

The synchronization primitives of asyncio are a bit difficult to use. Lock can only ensure that the code in async with is not executed at the same time, and Event does not support the use of asynchronous context managers, which is troublesome to use repeatedly, so I came up with a good way:

class TaskCoordinator:
    def __init__(self) -> None:
        self._enter = asyncio.Lock()
        self._exit = asyncio.Lock()
        self._enter._locked = True
        self._exit._locked = True

    async def run(self):
        self._enter.release()
        await self._exit.acquire()

    async def __aenter__(self):
        await self._enter.acquire()

    async def __aexit__(self,exc,excv,track):
        self._exit.release()

The async with statement will wait before the unlock call, and unlock will also wait until the async with statement exits. If you use run in coroutine A and async with in coroutine B, the execution order will be:
the part before the run call → the part in async with → the part after the run call.
This is much more convenient than using Events repeatedly.I hope there will be a similar synchronous method in asyncio

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions