@@ -156,8 +156,35 @@ class _PoolCache(dict):
156156 """
157157 def __init__ (self , / , * args , notifier = None , ** kwds ):
158158 self .notifier = notifier
159+ self ._async_registration_lock = threading .Lock ()
160+ self ._accept_async_results = True
159161 super ().__init__ (* args , ** kwds )
160162
163+ def register_async_result (self , result ):
164+ with self ._async_registration_lock :
165+ if not self ._accept_async_results :
166+ raise ValueError ("Pool not running" )
167+ self [result ._job ] = result
168+
169+ def stop_async_submissions (self ):
170+ with self ._async_registration_lock :
171+ self ._accept_async_results = False
172+
173+ def cancel_async_results (self , * , except_job = None ):
174+ for job , result in self .copy ().items ():
175+ if job != except_job and isinstance (result , ApplyResult ):
176+ # The worker handler was already notified to stop.
177+ self .pop (job )
178+ result ._cancel ()
179+
180+ def publish (self , job , index , value ):
181+ thread = threading .current_thread ()
182+ thread ._publishing_pool_job = job
183+ try :
184+ self [job ]._set (index , value )
185+ finally :
186+ del thread ._publishing_pool_job
187+
161188 def __delitem__ (self , item ):
162189 super ().__delitem__ (item )
163190
@@ -241,17 +268,18 @@ def __init__(self, processes=None, initializer=None, initargs=(),
241268
242269
243270 self ._task_handler = threading .Thread (
244- target = Pool ._handle_tasks ,
245- args = (self ._taskqueue , self . _quick_put , self ._outqueue ,
246- self ._pool , self ._cache )
271+ target = Pool ._run_handler ,
272+ args = (self ._cache , Pool . _handle_tasks , self ._taskqueue ,
273+ self ._quick_put , self ._outqueue , self . _pool )
247274 )
248275 self ._task_handler .daemon = True
249276 self ._task_handler ._state = RUN
250277 self ._task_handler .start ()
251278
252279 self ._result_handler = threading .Thread (
253- target = Pool ._handle_results ,
254- args = (self ._outqueue , self ._quick_get , self ._cache )
280+ target = Pool ._run_handler ,
281+ args = (self ._cache , Pool ._handle_results , self ._outqueue ,
282+ self ._quick_get )
255283 )
256284 self ._result_handler .daemon = True
257285 self ._result_handler ._state = RUN
@@ -438,6 +466,7 @@ def apply_async(self, func, args=(), kwds={}, callback=None,
438466 '''
439467 self ._check_running ()
440468 result = ApplyResult (self , callback , error_callback )
469+ self ._cache .register_async_result (result )
441470 self ._taskqueue .put (([(result ._job , 0 , func , args , kwds )], None ))
442471 return result
443472
@@ -468,6 +497,8 @@ def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
468497 task_batches = Pool ._get_tasks (func , iterable , chunksize )
469498 result = MapResult (self , chunksize , len (iterable ), callback ,
470499 error_callback = error_callback )
500+ if result ._number_left :
501+ self ._cache .register_async_result (result )
471502 self ._taskqueue .put (
472503 (
473504 self ._guarded_task_generation (result ._job ,
@@ -540,6 +571,15 @@ def _handle_workers(cls, cache, taskqueue, ctx, Process, processes,
540571 taskqueue .put (None )
541572 util .debug ('worker handler exiting' )
542573
574+ @staticmethod
575+ def _run_handler (cache , target , * args ):
576+ try :
577+ target (* args , cache )
578+ finally :
579+ thread = threading .current_thread ()
580+ if getattr (thread , '_cancel_pending_results' , False ):
581+ cache .cancel_async_results ()
582+
543583 @staticmethod
544584 def _handle_tasks (taskqueue , put , outqueue , pool , cache ):
545585 thread = threading .current_thread ()
@@ -557,7 +597,7 @@ def _handle_tasks(taskqueue, put, outqueue, pool, cache):
557597 except Exception as e :
558598 job , idx = task [:2 ]
559599 try :
560- cache [ job ]. _set ( idx , (False , e ))
600+ cache . publish ( job , idx , (False , e ))
561601 except KeyError :
562602 pass
563603 else :
@@ -608,7 +648,7 @@ def _handle_results(outqueue, get, cache):
608648
609649 job , i , obj = task
610650 try :
611- cache [ job ]. _set ( i , obj )
651+ cache . publish ( job , i , obj )
612652 except KeyError :
613653 pass
614654 task = job = obj = None
@@ -625,7 +665,7 @@ def _handle_results(outqueue, get, cache):
625665 continue
626666 job , i , obj = task
627667 try :
628- cache [ job ]. _set ( i , obj )
668+ cache . publish ( job , i , obj )
629669 except KeyError :
630670 pass
631671 task = job = obj = None
@@ -703,6 +743,7 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
703743 taskqueue_buffersize_semaphores ):
704744 # this is guaranteed to only be called once
705745 util .debug ('finalizing pool' )
746+ cache .stop_async_submissions ()
706747
707748 # Notify that the worker_handler state has been changed so the
708749 # _handle_workers loop can be unblocked (and exited) in order to
@@ -730,7 +771,8 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
730771 # We must wait for the worker handler to exit before terminating
731772 # workers because we don't want workers to be restarted behind our back.
732773 util .debug ('joining worker handler' )
733- if threading .current_thread () is not worker_handler :
774+ current_thread = threading .current_thread ()
775+ if current_thread is not worker_handler :
734776 worker_handler .join ()
735777
736778 # Terminate workers which haven't already finished.
@@ -741,13 +783,23 @@ def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
741783 p .terminate ()
742784
743785 util .debug ('joining task handler' )
744- if threading . current_thread () is not task_handler :
786+ if current_thread is not task_handler :
745787 task_handler .join ()
746788
747789 util .debug ('joining result handler' )
748- if threading . current_thread () is not result_handler :
790+ if current_thread is not result_handler :
749791 result_handler .join ()
750792
793+ # A callback may be publishing a result on the terminating thread.
794+ # Leave that result alone until its handler exits, but wake waiters
795+ # on other results now, including the callback itself.
796+ publishing_job = None
797+ if current_thread in (task_handler , result_handler ):
798+ publishing_job = getattr (current_thread , '_publishing_pool_job' ,
799+ None )
800+ current_thread ._cancel_pending_results = publishing_job is not None
801+ cache .cancel_async_results (except_job = publishing_job )
802+
751803 if pool and hasattr (pool [0 ], 'terminate' ):
752804 util .debug ('joining pool workers' )
753805 for p in pool :
@@ -786,7 +838,6 @@ def __init__(self, pool, callback, error_callback):
786838 self ._cache = pool ._cache
787839 self ._callback = callback
788840 self ._error_callback = error_callback
789- self ._cache [self ._job ] = self
790841
791842 def ready (self ):
792843 return self ._event .is_set ()
@@ -808,6 +859,12 @@ def get(self, timeout=None):
808859 else :
809860 raise self ._value
810861
862+ def _cancel (self ):
863+ self ._success = False
864+ self ._value = RuntimeError ("Pool has been terminated" )
865+ self ._pool = None
866+ self ._event .set ()
867+
811868 def _set (self , i , obj ):
812869 self ._success , self ._value = obj
813870 try :
@@ -849,7 +906,6 @@ def __init__(self, pool, chunksize, length, callback, error_callback):
849906 if chunksize <= 0 :
850907 self ._number_left = 0
851908 self ._event .set ()
852- del self ._cache [self ._job ]
853909 else :
854910 self ._number_left = length // chunksize + bool (length % chunksize )
855911
0 commit comments