2017-03-16 127 views
0

我想用泳池對象的close()方法正常停止泳池工作人員,但terminate()那些在10秒內未完成執行的泳池工作人員。多處理線程池關閉,超時

started_at = int(time.time()) 
p.close() # this is blocking 
if (int(time.time()) - started_at >= 10): 
    p.terminate() 

就是這樣。任何想法? :)

我也想過發送SIGTERM s的線程,但他們共享相同的PID,所以我不能這樣做。

+0

對不起,這是線程池在我的情況。修復它 –

回答

1

如果您使用的是線程池,則可以使用全局變量(例如stopthreads)。當它被設置爲True

在工作線程的功能(S)的運行應該經常檢查這個變量並退出:

def worker(data): 
    while True: 
     if stopthreads: 
      return None 
     # do other things 
0

看來我第一次沒有得到這個問題。

你也許可以在p.close()呼叫發送到另一個進程,使用apply_async例如,看看apply_async調用不按時完成,只需調用p.terminate()

欲瞭解更多有關apply_async的信息,請參考docs