使用timeou关闭多处理线程池

2024-05-15 02:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

像这样。有什么想法吗?:)

我还考虑过向线程发送SIGTERM,但是它们共享相同的pid,所以我不能这样做。在


Tags: 对象方法closetimeisblockingthis线程
2条回答

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

您也许可以将p.close()调用发送到另一个进程,例如使用apply_async,看看{}调用是否没有及时完成,只需调用p.terminate()。在

有关apply_async的更多信息,请参考docs。在

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

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

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

相关问题 更多 >

    热门问题