Skip to content

Commit e3344dc

Browse files
Expose defer_to_threadpool in the module API (#19032)
1 parent bcbbccc commit e3344dc

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

changelog.d/19032.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Expose a `defer_to_threadpool` function in the Synapse Module API that allows modules to run a function on a separate thread in a custom threadpool.

synapse/module_api/__init__.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343

4444
from twisted.internet import defer
4545
from twisted.internet.interfaces import IDelayedCall
46+
from twisted.python.threadpool import ThreadPool
4647
from twisted.web.resource import Resource
4748

4849
from synapse.api import errors
@@ -79,6 +80,7 @@
7980
from synapse.http.site import SynapseRequest
8081
from synapse.logging.context import (
8182
defer_to_thread,
83+
defer_to_threadpool,
8284
make_deferred_yieldable,
8385
run_in_background,
8486
)
@@ -1733,6 +1735,33 @@ async def defer_to_thread(
17331735
"""
17341736
return await defer_to_thread(self._hs.get_reactor(), f, *args, **kwargs)
17351737

1738+
async def defer_to_threadpool(
1739+
self,
1740+
threadpool: ThreadPool,
1741+
f: Callable[P, T],
1742+
*args: P.args,
1743+
**kwargs: P.kwargs,
1744+
) -> T:
1745+
"""Runs the given function in a separate thread from the given thread pool.
1746+
1747+
Allows specifying a custom thread pool instead of using the default Synapse
1748+
one. To use the default Synapse threadpool, use `defer_to_thread` instead.
1749+
1750+
Added in Synapse v1.140.0.
1751+
1752+
Args:
1753+
threadpool: The thread pool to use.
1754+
f: The function to run.
1755+
args: The function's arguments.
1756+
kwargs: The function's keyword arguments.
1757+
1758+
Returns:
1759+
The return value of the function once ran in a thread.
1760+
"""
1761+
return await defer_to_threadpool(
1762+
self._hs.get_reactor(), threadpool, f, *args, **kwargs
1763+
)
1764+
17361765
async def check_username(self, username: str) -> None:
17371766
"""Checks if the provided username uses the grammar defined in the Matrix
17381767
specification, and is already being used by an existing user.

0 commit comments

Comments
 (0)