gh-128002: use `_PyObject_SetMaybeWeakref` when creating tasks in asyncio by kumaraditya303 · Pull Request #128885 · python/cpython · GitHub
Skip to content

gh-128002: use _PyObject_SetMaybeWeakref when creating tasks in asyncio - #128885

Merged
kumaraditya303 merged 5 commits into
python:mainfrom
kumaraditya303:maybe-weakref
Jan 24, 2025
Merged

kumaraditya303 merged 5 commits into
python:mainfrom
kumaraditya303:maybe-weakref

Conversation

@kumaraditya303

@kumaraditya303 kumaraditya303 commented Jan 15, 2025

Copy link
Copy Markdown
Contributor

@colesbury

Copy link
Copy Markdown
Contributor

@kumaraditya303

Copy link
Copy Markdown
Contributor Author

I think the following code appears to catch that bug:

import asyncio
import threading


def func():
    loop = asyncio.EventLoop()

    async def coro():
        await asyncio.sleep(0.01)

    lock = threading.Lock()
    count = 0
    async def main():
        nonlocal count
        while True:
            with lock:
                asyncio.create_task(coro())
                count = len(asyncio.all_tasks(loop))

    th = threading.Thread(target=loop.run_until_complete, args=(main(),))
    th.start()

    def check():
        with lock:
            assert count == len(asyncio.all_tasks(loop))

    threads = [threading.Thread(target=check) for _ in range(10)]
    for t in threads:
        t.start()

    for t in threads:
        t.join()


func()

Without the fix, I see many assertion errors and with it there isn't any.

@kumaraditya303

Copy link
Copy Markdown
Contributor Author

@colesbury Added test based on the above code.

@kumaraditya303

Copy link
Copy Markdown
Contributor Author

@kumaraditya303
kumaraditya303 merged commit 8e0b360 into python:main Jan 24, 2025
@kumaraditya303
kumaraditya303 deleted the maybe-weakref branch January 24, 2025 15:43
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