Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Lib/test/test_asyncio/test_free_threading.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import threading
import unittest
from threading import Thread
from unittest import TestCase
Expand Down Expand Up @@ -58,6 +59,38 @@ def runner():
with threading_helper.start_threads(threads):
pass

def test_all_tasks_different_thread(self) -> None:
loop = None
started = threading.Event()

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

lock = threading.Lock()
count = 0

async def main():
nonlocal count, loop
loop = asyncio.get_running_loop()
started.set()
for i in range(1000):
with lock:
asyncio.create_task(coro())
count = len(self.all_tasks(loop))

runner = threading.Thread(target=lambda: asyncio.run(main()))

def check():
started.wait()
with lock:
self.assertEqual(count, len(self.all_tasks(loop)))

threads = [threading.Thread(target=check) for _ in range(10)]
threads.append(runner)

with threading_helper.start_threads(threads):
pass

def test_run_coroutine_threadsafe(self) -> None:
results = []

Expand Down
6 changes: 6 additions & 0 deletions Modules/_asynciomodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "pycore_llist.h" // struct llist_node
#include "pycore_modsupport.h" // _PyArg_CheckPositional()
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_object.h" // _PyObject_SetMaybeWeakref
#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
#include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
#include "pycore_pystate.h" // _PyThreadState_GET()
Expand Down Expand Up @@ -2466,6 +2467,11 @@ _asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop,
if (task_call_step_soon(state, self, NULL)) {
return -1;
}
#ifdef Py_GIL_DISABLED
// This is required so that _Py_TryIncref(self)
// works correctly in non-owning threads.
_PyObject_SetMaybeWeakref((PyObject *)self);
#endif
register_task(state, self);
return 0;
}
Expand Down
Loading