Skip to content

Commit 672119c

Browse files
committed
asynchronous/thread: add pool decorator parameter
The `pool` parameter allows to pass an instance of ThreadPool as executor for the decorated function instead of running it within a new thread. Thus allowing better control of used resources when running a decorated function multiple times. Signed-off-by: Matteo Cafasso <[email protected]>
1 parent 7f940c2 commit 672119c

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

pebble/asynchronous/thread.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from functools import wraps
2121

2222
from pebble import common
23+
from pebble.pool.thread import ThreadPool
2324

2425

2526
def thread(*args, **kwargs) -> Callable:
@@ -38,14 +39,30 @@ def thread(*args, **kwargs) -> Callable:
3839
return common.decorate_function(_thread_wrapper, *args, **kwargs)
3940

4041

41-
def _thread_wrapper(function: Callable, name: str, daemon: bool, *_) -> Callable:
42+
def _thread_wrapper(
43+
function: Callable,
44+
name: str,
45+
daemon: bool,
46+
_timeout: float,
47+
_mp_context,
48+
pool: ThreadPool
49+
) -> Callable:
50+
if pool is not None:
51+
if not isinstance(pool, ThreadPool):
52+
raise TypeError('Pool expected to be ThreadPool')
53+
4254
@wraps(function)
4355
def wrapper(*args, **kwargs) -> asyncio.Future:
4456
loop = common.get_asyncio_loop()
45-
future = loop.create_future()
4657

47-
common.launch_thread(
48-
name, _function_handler, daemon, function, args, kwargs, future)
58+
if pool is not None:
59+
future = loop.run_in_executor(pool, function, *args, **kwargs)
60+
else:
61+
future = loop.create_future()
62+
63+
common.launch_thread(
64+
name, _function_handler, daemon,
65+
function, args, kwargs, future)
4966

5067
return future
5168

0 commit comments

Comments
 (0)