run_in_executor -> _run_in_thread

This commit is contained in:
AF 2022-11-04 08:05:55 +00:00
parent 90e7cd39c6
commit c9cdbf86a6

View File

@ -3,6 +3,7 @@ import concurrent.futures
import json import json
import pathlib import pathlib
import pickle import pickle
import threading
import traceback import traceback
from io import StringIO from io import StringIO
from typing import Any, Optional, IO, Type, Hashable from typing import Any, Optional, IO, Type, Hashable
@ -242,9 +243,23 @@ class DbConnection:
self.__path_recover.touch() self.__path_recover.touch()
self._finish_recovery_sync() 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): async def _build_file(self, db: dict):
with concurrent.futures.ThreadPoolExecutor() as pool: await self._run_in_thread(self._build_file_sync, db)
await self.__loop.run_in_executor(pool, self._build_file_sync, db)
def _rebuild_file_sync(self, db: dict): def _rebuild_file_sync(self, db: dict):
if self.__path_recover.exists(): if self.__path_recover.exists():
@ -255,8 +270,7 @@ class DbConnection:
self._build_file_sync(db) self._build_file_sync(db)
async def _rebuild_file(self, db: dict): async def _rebuild_file(self, db: dict):
with concurrent.futures.ThreadPoolExecutor() as pool: await self._run_in_thread(self._rebuild_file_sync, db)
await self.__loop.run_in_executor(pool, self._rebuild_file_sync, db)
async def _reload(self): async def _reload(self):
self.__file.close() self.__file.close()