Skip to content
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

Fix from_thread.run(_sync)? failing in any thread running Trio #2535

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions newsfragments/2191.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`trio.from_thread.run` and `trio.from_thread.run_sync` no longer raise `RuntimeError` when used to enter a thread running Trio from a different thread running Trio.
11 changes: 8 additions & 3 deletions trio/_threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,13 +245,18 @@ def _run_fn_as_system_task(cb, fn, *args, context, trio_token=None):
"this thread wasn't created by Trio, pass kwarg trio_token=..."
)

# Avoid deadlock by making sure we're not called from Trio thread
# Avoid deadlock by making sure we're not called from the same Trio thread we're
# trying to enter
try:
trio.lowlevel.current_task()
current_trio_token = trio.lowlevel.current_trio_token()
except RuntimeError:
pass
else:
raise RuntimeError("this is a blocking function; call it from a thread")
if trio_token == current_trio_token:
raise RuntimeError(
"this is a blocking function; using it to re-enter the current Trio "
"thread would cause a deadlock"
)

q = stdlib_queue.SimpleQueue()
trio_token.run_sync_soon(context.run, cb, q, fn, args)
Expand Down
11 changes: 10 additions & 1 deletion trio/tests/test_threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -818,7 +818,7 @@ def test_run_fn_as_system_task_catched_badly_typed_token():
from_thread_run_sync(_core.current_time, trio_token="Not TrioTokentype")


async def test_from_thread_inside_trio_thread():
async def test_from_thread_inside_same_trio_thread():
def not_called(): # pragma: no cover
assert False

Expand All @@ -827,6 +827,15 @@ def not_called(): # pragma: no cover
from_thread_run_sync(not_called, trio_token=trio_token)


async def test_from_thread_inside_different_trio_thread():
target_token = current_trio_token()

async def thread_fn():
return from_thread_run_sync(current_trio_token, trio_token=target_token)

assert target_token == await to_thread_run_sync(_core.run, thread_fn)


@pytest.mark.skipif(buggy_pypy_asyncgens, reason="pypy 7.2.0 is buggy")
def test_from_thread_run_during_shutdown():
save = []
Expand Down