-
Notifications
You must be signed in to change notification settings - Fork 798
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Opt: Patch aiofiles to reduce thread pool size
- Loading branch information
Showing
2 changed files
with
40 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import asyncio | ||
from functools import partial, wraps | ||
|
||
from module.logger import logger | ||
from module.webui.setting import cached_class_property | ||
|
||
|
||
class CachedThreadPoolExecutor: | ||
@cached_class_property | ||
def executor(cls): | ||
from concurrent.futures.thread import ThreadPoolExecutor | ||
pool = ThreadPoolExecutor(max_workers=5) | ||
logger.info('Patched ThreadPoolExecutor created') | ||
return pool | ||
|
||
|
||
def wrap(func): | ||
@wraps(func) | ||
async def run(*args, loop=None, executor=None, **kwargs): | ||
if loop is None: | ||
loop = asyncio.get_event_loop() | ||
if executor is None: | ||
executor = CachedThreadPoolExecutor.executor | ||
pfunc = partial(func, *args, **kwargs) | ||
return await loop.run_in_executor(executor, pfunc) | ||
|
||
return run | ||
|
||
|
||
def patch_executor(): | ||
""" | ||
Limit pool size in loop.run_in_executor | ||
so starlette.staticfiles -> aiofiles won't create tons of threads | ||
""" | ||
loop = asyncio.get_event_loop() | ||
loop.set_default_executor(CachedThreadPoolExecutor.executor) |