3131
3232CALLBACK_SERVER : str = os .getenv ("CALLBACK_SERVER" ) or ""
3333NUM_WORKERS = int (os .getenv ("NUM_WORKERS" ) or 1 )
34+ # Needs to be defined as a reference object, e.g. dict.
35+ _global = {"pool" : None }
3436
3537
3638def run_pending_tasks () -> None :
3739 """
3840 Send a new task to the pool if there is no busy task.
3941 If there is no pool running, start a new pool.
4042 """
41- global pool
42-
4343 # One task at a time.
44- tasks_in_queue = pool ._taskqueue .qsize ()
44+ tasks_in_queue = _global [ " pool" ] ._taskqueue .qsize ()
4545 if tasks_in_queue > 0 :
4646 return
4747
@@ -54,11 +54,11 @@ def run_pending_tasks() -> None:
5454 if sl .get_status ()["busy" ] is False :
5555 sl .busy ("Parsing file" ) # Sets busy true
5656 # Extra None check for typing
57- if (not is_pool_running (pool )) or pool is None :
57+ if (not is_pool_running ()) or _global [ " pool" ] is None :
5858 # Spawn pool if not running
59- pool = mp .Pool (processes = NUM_WORKERS , initializer = process . init )
59+ _global [ " pool" ] = mp .Pool (processes = NUM_WORKERS )
6060 # Perform task at running pool
61- pool .apply_async (process_file , args = (sl .filename ,))
61+ _global [ " pool" ] .apply_async (process_file , args = (sl .filename ,))
6262
6363
6464def process_file (filename : str ):
@@ -183,28 +183,31 @@ def send_error_to_callback_server(filename: str, out_path: str, message: str) ->
183183 keep_or_delete_file (r , out_path )
184184
185185
186- def is_pool_running (pool : Optional [ Pool ] ) -> bool :
186+ def is_pool_running () -> bool :
187187 """
188188 Check if the pool is running by trying to execute a dummy function.
189189 """
190- if pool is None :
190+ if _global [ " pool" ] is None :
191191 return False
192192 try :
193- pool .apply_async (lambda : None )
193+ _global [ " pool" ] .apply_async (lambda : None )
194194 except ValueError as e :
195195 if str (e ) == "Pool not running" :
196196 return False
197197 return True
198198
199199
200- # Pool needs to be defined after the functions it will execute.
201- # https://stackoverflow.com/questions/41385708/multiprocessing-example-giving-attributeerror#comment101561695_42383397
202- pool = None
200+ def terminate_pool () -> None :
201+ """
202+ Terminate the pool if it is running.
203+ """
204+ _global ["pool" ].terminate ()
205+
203206
204- if __name__ == "__main__" :
207+ def run_background () :
205208 # Can't use fork with the gpu.
206209 mp .set_start_method ("spawn" , force = True )
207- pool = mp .Pool (processes = NUM_WORKERS , initializer = process . init )
210+ _global [ " pool" ] = mp .Pool (processes = NUM_WORKERS )
208211
209212 # It is ugly, but it is also used here:
210213 # https://pypi.org/project/schedule/
0 commit comments