Skip to content

Commit

Permalink
Merge pull request #3163 from graingert/avoid-threading-identity
Browse files Browse the repository at this point in the history
use get_running_loop to choose between call_soon and call_soon_thread…
  • Loading branch information
bdarnell committed Jun 23, 2022
2 parents 7a80716 + d1ce56d commit a5a6b03
Showing 1 changed file with 7 additions and 10 deletions.
17 changes: 7 additions & 10 deletions tornado/platform/asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,15 +137,8 @@ def initialize( # type: ignore
f"IOLoop {existing_loop} already associated with asyncio loop {asyncio_loop}"
)

self._thread_identity = 0

super().initialize(**kwargs)

def assign_thread_identity() -> None:
self._thread_identity = threading.get_ident()

self.add_callback(assign_thread_identity)

def close(self, all_fds: bool = False) -> None:
self.closing = True
for fd in list(self.handlers):
Expand Down Expand Up @@ -242,10 +235,14 @@ def remove_timeout(self, timeout: object) -> None:
timeout.cancel() # type: ignore

def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
if threading.get_ident() == self._thread_identity:
call_soon = self.asyncio_loop.call_soon
else:
try:
if asyncio.get_running_loop() is self.asyncio_loop:
call_soon = self.asyncio_loop.call_soon
else:
call_soon = self.asyncio_loop.call_soon_threadsafe
except RuntimeError:
call_soon = self.asyncio_loop.call_soon_threadsafe

try:
call_soon(self._run_callback, functools.partial(callback, *args, **kwargs))
except RuntimeError:
Expand Down

0 comments on commit a5a6b03

Please sign in to comment.