11import asyncio
22import multiprocessing
3- from typing import Callable , Iterable , Optional , Union
3+ from multiprocessing .context import BaseContext
4+ from typing import Callable , Iterable , Optional , Union , Sized
45
56from dispatcher .worker .task import work_loop
67
78
89class ProcessProxy :
9- def __init__ (self , args : Iterable , finished_queue : multiprocessing .Queue , target : Callable = work_loop ) -> None :
10- self .message_queue : multiprocessing .Queue = multiprocessing .Queue ()
11- self ._process = multiprocessing .Process (target = target , args = tuple (args ) + (self .message_queue , finished_queue ))
10+ def __init__ (self , args : Iterable , finished_queue : multiprocessing .Queue , target : Callable = work_loop , ctx : BaseContext = multiprocessing ) -> None :
11+ self .message_queue : multiprocessing .Queue = ctx .Queue ()
12+ self ._process = ctx .Process (target = target , args = tuple (args ) + (self .message_queue , finished_queue ))
1213
1314 def start (self ) -> None :
1415 self ._process .start ()
@@ -37,8 +38,11 @@ def terminate(self) -> None:
3738
3839
3940class ProcessManager :
41+ mp_context = 'fork'
42+
4043 def __init__ (self ) -> None :
41- self .finished_queue : multiprocessing .Queue = multiprocessing .Queue ()
44+ self .ctx = multiprocessing .get_context (self .mp_context )
45+ self .finished_queue : multiprocessing .Queue = self .ctx .Queue ()
4246 self ._loop = None
4347
4448 def get_event_loop (self ):
@@ -47,8 +51,16 @@ def get_event_loop(self):
4751 return self ._loop
4852
4953 def create_process (self , args : Iterable [int | str ], ** kwargs ) -> ProcessProxy :
50- return ProcessProxy (args , self .finished_queue , ** kwargs )
54+ return ProcessProxy (args , self .finished_queue , ctx = self . ctx , ** kwargs )
5155
5256 async def read_finished (self ) -> dict [str , Union [str , int ]]:
5357 message = await self .get_event_loop ().run_in_executor (None , self .finished_queue .get )
5458 return message
59+
60+
61+ class ForkServerManager (ProcessManager ):
62+ mp_context = 'forkserver'
63+
64+ def __init__ (self , preload_modules : Sized = ()):
65+ super ().__init__ ()
66+ self .ctx .set_forkserver_preload (preload_modules )
0 commit comments