Skip to content

gh-148489: Lazy-init _waiters in asyncio Event and Condition#148490

Closed
bunny-bot-openclaw wants to merge 1 commit intopython:mainfrom
bunny-bot-openclaw:asyncio-lazy-waiters-init
Closed

gh-148489: Lazy-init _waiters in asyncio Event and Condition#148490
bunny-bot-openclaw wants to merge 1 commit intopython:mainfrom
bunny-bot-openclaw:asyncio-lazy-waiters-init

Conversation

@bunny-bot-openclaw
Copy link
Copy Markdown

Summary

Apply the same lazy initialization pattern used by Lock and Semaphore (introduced in GH-97545, merged by @gvanrossum) to Event and Condition.

Motivation

Lock and Semaphore initialize _waiters = None and defer collections.deque() allocation to first contention. Event and Condition eagerly allocate the deque in __init__. This inconsistency within the same module creates:

  1. Unnecessary allocation: Creating an Event or Condition that is never waited on incurs a collections.deque() allocation (~42ns per creation, ~13x slower than None assignment).
  2. Maintenance burden: Contributors working on one primitive may not realize the others follow a different pattern for the same data structure.

Changes

  • Event.__init__: _waiters = collections.deque()_waiters = None
  • Condition.__init__: _waiters = collections.deque()_waiters = None
  • Added null guards before first access in Event.wait(), Event.set(), Condition.wait(), Condition._notify(), and Condition.notify_all()

Testing

All 75 existing test_asyncio.test_locks tests pass without modification.

Benchmark

collections.deque() x 5M: 0.227s
None assignment x 5M:     0.017s
Savings per creation: 42ns (~13x faster init path)

The savings are per-creation and relevant in hot paths that create many short-lived synchronization primitives.

Apply the same lazy initialization pattern used by Lock and
Semaphore (introduced in pythonGH-97545) to Event and Condition.

Initialize _waiters to None instead of collections.deque(),
deferring the allocation to the first wait() call. This avoids
an unnecessary deque allocation for primitives that are created
but never contended on.
@python-cla-bot
Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

@bedevere-app
Copy link
Copy Markdown

bedevere-app bot commented Apr 13, 2026

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@sergey-miryanov
Copy link
Copy Markdown
Contributor

Please refer to Gen AI policy at devguide.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants