Skip to content

Commit a4852c5

Browse files
committed
Close thread loop adapter from the correct thread
1 parent 8cb31c1 commit a4852c5

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

scrapy_playwright/_utils.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,11 @@ def _deferred_from_coro(cls, coro) -> Deferred:
140140
return dfd
141141

142142
@classmethod
143-
def start(cls, caller_id: int) -> None:
144-
cls._stop_events[caller_id] = asyncio.Event()
143+
def start(cls, download_handler_id: int) -> None:
144+
"""Start the event loop in a new thread if not already started.
145+
Should be called from the Scrapy thread.
146+
"""
147+
cls._stop_events[download_handler_id] = asyncio.Event()
145148
if not getattr(cls, "_loop", None):
146149
policy = asyncio.DefaultEventLoopPolicy()
147150
if platform.system() == "Windows":
@@ -155,9 +158,11 @@ def start(cls, caller_id: int) -> None:
155158
asyncio.run_coroutine_threadsafe(cls._process_queue(), cls._loop)
156159

157160
@classmethod
158-
def stop(cls, caller_id: int) -> None:
159-
"""Wait until all handlers are closed to stop the event loop and join the thread."""
160-
cls._stop_events[caller_id].set()
161+
def stop(cls, download_handler_id: int) -> None:
162+
"""Wait until all handlers are closed to stop the event loop and join the thread.
163+
Should be called from the Scrapy thread.
164+
"""
165+
cls._stop_events[download_handler_id].set()
161166
if all(ev.is_set() for ev in cls._stop_events.values()):
162167
asyncio.run_coroutine_threadsafe(cls._coro_queue.join(), cls._loop)
163168
cls._loop.call_soon_threadsafe(cls._loop.stop)

scrapy_playwright/handler.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,8 @@ async def close(self) -> None:
363363
logger.info("Closing download handler")
364364
await super().close()
365365
await self._close()
366+
if self.config.use_threaded_loop:
367+
_ThreadedLoopAdapter.stop(id(self))
366368

367369
else:
368370

@@ -371,6 +373,8 @@ def close(self) -> Deferred: # pylint: disable=invalid-overridden-method
371373
logger.info("Closing download handler")
372374
yield super().close()
373375
yield self._deferred_from_coro(self._close())
376+
if self.config.use_threaded_loop:
377+
_ThreadedLoopAdapter.stop(id(self))
374378

375379
async def _close(self) -> None:
376380
with suppress(TargetClosedError):
@@ -383,8 +387,6 @@ async def _close(self) -> None:
383387
await self.playwright_context_manager.__aexit__()
384388
if self.playwright:
385389
await self.playwright.stop()
386-
if self.config.use_threaded_loop:
387-
_ThreadedLoopAdapter.stop(id(self))
388390

389391
if _SCRAPY_ASYNC_API:
390392

0 commit comments

Comments
 (0)