|
4 | 4 | from typing import Callable, TypeVar, Any, Awaitable, Optional, Type, Union |
5 | 5 |
|
6 | 6 | try: |
7 | | - import multiprocess as mp |
8 | 7 | from multiprocess import Process, Pipe |
9 | 8 | from multiprocess.connection import Connection |
10 | | - |
11 | | - mp.set_start_method(method="spawn", force=True) |
12 | 9 | except ImportError: |
13 | 10 | Process: Optional[Type] = None |
14 | 11 | Pipe: Optional[Type] = None |
@@ -106,11 +103,18 @@ async def calculate_in_subprocess(func: Callable[..., Union[T, Awaitable[T]]], * |
106 | 103 | return result |
107 | 104 |
|
108 | 105 |
|
109 | | -def _inner(tx: Connection, fun: Callable[..., Union[T, Awaitable[T]]], *a, **kw_args) -> None: |
| 106 | +def _inner(tx: Connection, fun: Callable[..., Union[T, Awaitable[T]]], *a, new_thread: bool = False, **kw_args) -> None: |
110 | 107 | """ This runs in another process. """ |
111 | 108 |
|
112 | 109 | event_loop = None |
113 | 110 | if inspect.iscoroutinefunction(fun): |
| 111 | + if not new_thread: # see https://stackoverflow.com/a/79785720/10975692 |
| 112 | + import threading |
| 113 | + t = threading.Thread(target=_inner, args=(tx, fun, *a), kwargs=(kw_args | {"new_thread": True})) |
| 114 | + t.start() |
| 115 | + t.join() |
| 116 | + return |
| 117 | + |
114 | 118 | event_loop = asyncio.new_event_loop() |
115 | 119 | asyncio.set_event_loop(event_loop) |
116 | 120 |
|
|
0 commit comments