Skip to content

Commit

Permalink
Fix from_thread.run(_sync?) not setting sniffio on asyncio
Browse files Browse the repository at this point in the history
This also fixes a deadlock when using start_blocking_portal("asyncio")
on a non-asyncio async backend known to sniffio.

Fixes agronholm#523.
  • Loading branch information
gschaffner committed Mar 9, 2023
1 parent 4d84f03 commit bf35657
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
9 changes: 9 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
the event loop to be closed
- Fixed ``current_effective_deadline()`` not returning ``-inf`` on asyncio when the
currently active cancel scope has been cancelled (PR by Ganden Schaffner)
- Fixed ``from_thread.run`` and ``from_thread.run_sync`` not setting sniffio on asyncio.
As a result:

- Fixed ``from_thread.run_sync`` failing when used to call sniffio-dependent functions
on asyncio
- Fixed ``from_thread.run`` failing when used to call sniffio-dependent functions on
asyncio from a thread running trio or curio
- Fixed deadlock when using ``from_thread.start_blocking_portal(backend="asyncio")``
in a thread running trio or curio (PR by Ganden Schaffner)

**3.6.1**

Expand Down
7 changes: 5 additions & 2 deletions src/anyio/_backends/_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -2035,8 +2035,10 @@ def run_async_from_thread(
token: object,
) -> T_Retval:
loop = cast(AbstractEventLoop, token)
f: concurrent.futures.Future[T_Retval] = asyncio.run_coroutine_threadsafe(
func(*args), loop
context = copy_context()
context.run(sniffio.current_async_library_cvar.set, "asyncio")
f: concurrent.futures.Future[T_Retval] = context.run(
asyncio.run_coroutine_threadsafe, func(*args), loop
)
return f.result()

Expand All @@ -2047,6 +2049,7 @@ def run_sync_from_thread(
@wraps(func)
def wrapper() -> None:
try:
sniffio.current_async_library_cvar.set("asyncio")
f.set_result(func(*args))
except BaseException as exc:
f.set_exception(exc)
Expand Down

0 comments on commit bf35657

Please sign in to comment.