多进程线程池关闭超时



我想用pool对象的close()方法优雅地停止池工作线程,但terminate()那些在10秒内没有完成执行的工作线程。

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

像这样的东西。知道吗?:)

我也想过将SIGTERM发送到线程,但它们共享相同的 pid,所以我不能这样做。

如果您使用的是线程池,则可以使用全局变量(例如 stopthreads (。

在工作线程中运行的函数应经常检查此变量,并在将其设置为 True 时退出:

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

好像我第一次没有收到这个问题。

您可以p.close()调用发送到另一个进程,例如使用 apply_async,并查看apply_async调用是否未及时完成,只需调用 p.terminate() 即可。

有关apply_async的更多信息,请参阅文档。

最新更新