【问题标题】:python SIGTERM not work when I use multiprocessing Pool当我使用多处理池时,python SIGTERM 不起作用
【发布时间】:2017-08-15 14:17:03
【问题描述】:

按预期正确代码: 从多处理导入池 进口信号 进口时间 导入操作系统

def consumer(i):
    while True:
        # print os.getpid()
        pass
def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGTERM, handler)
p = Pool(5)
p.map_async(consumer, [1 for i in range(5)])

while True:
    pass

p.terminate()
# p.close()
p.join()

================================================ ===

我发现了问题,当我使用map函数时,main func被阻塞了,只有在map函数完成时才会调用信号处理程序。 所以,使用“map_async”函数来解决这个问题要好得多。

这是我发现的:

纯粹在 C 中实现的长时间运行的计算(例如对大量文本进行正则表达式匹配)可以在任意时间内不间断地运行,而不管接收到任何信号。计算完成时将调用 Python 信号处理程序。

================================================ ===

我写了一个类似下面的程序,我希望在终端输入“kill pid”时在程序中退出/(如程序打印字符串),但它不起作用。是否有任何其他策略阻止 SIGTERM 进入主函数。

from multiprocessing import Pool
import signal
import time
import os

def consumer(i):
    while True:
        # print os.getpid()
        pass
def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGTERM, handler)
p = Pool(5)
p.map(consumer, [1 for i in range(5)])

p.terminate()
# p.close()
p.join()

【问题讨论】:

  • 您需要先拨打terminate,然后拨打join。反之亦然。
  • 我尝试先呼叫终止,然后加入。但这似乎不适用于我的问题,但也感谢您的帮助。 @noxdafox

标签: python-2.7 multiprocessing python-multiprocessing pool sigterm


【解决方案1】:

您需要使用map_async 方法作为map 一个块,直到结果尚未准备好。因此,在您的示例中,从未达到对 terminate 的调用。

【讨论】:

  • 请将答案标记为正确,以便其他人可以从中受益。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多