From c9cdbf86a67eaf817baf0bc23e0440b54c070362 Mon Sep 17 00:00:00 2001 From: timofey Date: Fri, 4 Nov 2022 08:05:55 +0000 Subject: [PATCH] run_in_executor -> _run_in_thread --- ptvp35/__init__.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/ptvp35/__init__.py b/ptvp35/__init__.py index 1df2ee4..bf85b82 100644 --- a/ptvp35/__init__.py +++ b/ptvp35/__init__.py @@ -3,6 +3,7 @@ import concurrent.futures import json import pathlib import pickle +import threading import traceback from io import StringIO from typing import Any, Optional, IO, Type, Hashable @@ -242,9 +243,23 @@ class DbConnection: self.__path_recover.touch() self._finish_recovery_sync() + def _run_in_thread(self, fn, *args, **kwargs) -> asyncio.Future: + future = self.__loop.create_future() + + def wrap(): + try: + result = fn(*args, **kwargs) + except Exception as exception: + self.__loop.call_soon_threadsafe(future.set_exception, exception) + else: + self.__loop.call_soon_threadsafe(future.set_result, result) + + threading.Thread(target=wrap).start() + + return future + async def _build_file(self, db: dict): - with concurrent.futures.ThreadPoolExecutor() as pool: - await self.__loop.run_in_executor(pool, self._build_file_sync, db) + await self._run_in_thread(self._build_file_sync, db) def _rebuild_file_sync(self, db: dict): if self.__path_recover.exists(): @@ -255,8 +270,7 @@ class DbConnection: self._build_file_sync(db) async def _rebuild_file(self, db: dict): - with concurrent.futures.ThreadPoolExecutor() as pool: - await self.__loop.run_in_executor(pool, self._rebuild_file_sync, db) + await self._run_in_thread(self._rebuild_file_sync, db) async def _reload(self): self.__file.close()