Skip to content

Condition.notify() fails when shared lock is held #1319

Description

@jpgxs

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

AnyIO version

4.14

Python version

3.11

What happened?

When using a Condition with an existing lock, it's not possible to call notify(...) unless the lock was acquired via the condition.

This makes it difficult to use multiple conditions which share the same lock (i.e., when different types of waiter depend on the same underlying state).

For example:

async with self._lock:
    mutate_state()

    if pending_changed:
        # !! RuntimeError: The current task is not holding the underlying lock.
        self._pending_condition.notify()

    if ready_changed:
        self._ready_condition.notify()

To work around this, I think the only solutions would be to:

a. Use a single condition to notify every waiter of every change
b. Acquire and release the lock twice, losing the atomicity of the state change and the notifications

How can we reproduce the bug?

import anyio

async def async_main():
    lock = anyio.Lock()
    cond = anyio.Condition(lock)
    async with lock:
        cond.notify()  # !! RuntimeError

anyio.run(async_main)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions