From 0be744fc8ee60d06152c17f1afd2ebd46a5812c0 Mon Sep 17 00:00:00 2001 From: Vladimir Solomatin Date: Tue, 16 Oct 2018 20:44:55 +0300 Subject: [PATCH] Add `run_in_executor` function to aiomisc/thread_pool.py --- aiomisc/thread_pool.py | 8 ++++++++ tests/test_thread_pool.py | 19 ++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/aiomisc/thread_pool.py b/aiomisc/thread_pool.py index 68070b66..b5f7a59e 100644 --- a/aiomisc/thread_pool.py +++ b/aiomisc/thread_pool.py @@ -82,6 +82,14 @@ def __del__(self): self.shutdown() +async def run_in_executor(func, *args, **kwargs): + loop = asyncio.get_event_loop() + + return await loop.run_in_executor( + None, partial(func, *args, **kwargs) + ) + + def threaded(func): @wraps(func) async def wrap(*args, **kwargs): diff --git a/tests/test_thread_pool.py b/tests/test_thread_pool.py index fbb18d15..e3e71c15 100644 --- a/tests/test_thread_pool.py +++ b/tests/test_thread_pool.py @@ -1,10 +1,11 @@ import asyncio from contextlib import suppress +from functools import partial import pytest import time -from aiomisc.thread_pool import ThreadPoolExecutor, threaded +from aiomisc.thread_pool import ThreadPoolExecutor, run_in_executor, threaded @pytest.fixture @@ -36,6 +37,22 @@ async def test_threaded(executor: ThreadPoolExecutor, timer): ) +@pytest.mark.asyncio +async def test_run_in_executor(executor: ThreadPoolExecutor, timer): + assert executor + + sleep = partial(run_in_executor, time.sleep) + + with timer(1): + await asyncio.gather( + sleep(1), + sleep(1), + sleep(1), + sleep(1), + sleep(1), + ) + + @pytest.mark.asyncio async def test_threaded_exc(executor: ThreadPoolExecutor): assert executor