【问题标题】:python multiprocessing pool timeoutpython多处理池超时
【发布时间】:2016-12-07 07:13:12
【问题描述】:

我想使用multiprocessing.Pool,但 multiprocessing.Pool 在超时后无法中止任务。我找到了solution 并进行了一些修改。

from multiprocessing import util, Pool, TimeoutError
from multiprocessing.dummy import Pool as ThreadPool
import threading
import sys
from functools import partial
import time


def worker(y):
    print("worker sleep {} sec, thread: {}".format(y, threading.current_thread()))
    start = time.time()
    while True:
       if time.time() - start >= y:
           break
       time.sleep(0.5)
       # show work progress
       print(y)
    return y


def collect_my_result(result):
    print("Got result {}".format(result))


def abortable_worker(func, *args, **kwargs):
    timeout = kwargs.get('timeout', None)
    p = ThreadPool(1)
    res = p.apply_async(func, args=args)
    try:
        # Wait timeout seconds for func to complete.
        out = res.get(timeout)
    except TimeoutError:
        print("Aborting due to timeout {}".format(args[1]))
        # kill worker itself when get TimeoutError
        sys.exit(1)
    else:
        return out


def empty_func():
    pass


if __name__ == "__main__":
    TIMEOUT = 4
    util.log_to_stderr(util.DEBUG)
    pool = Pool(processes=4)

    # k - time to job sleep
    featureClass = [(k,) for k in range(20, 0, -1)]  # list of arguments
    for f in featureClass:
        # check available worker
        pool.apply(empty_func)

        # run job with timeout
        abortable_func = partial(abortable_worker, worker, timeout=TIMEOUT)
        pool.apply_async(abortable_func, args=f, callback=collect_my_result)

    time.sleep(TIMEOUT)
    pool.terminate()
    print("exit")

主要修改 - 使用 sys.exit(1) 退出工作进程。它是杀死工作进程并杀死工作线程,但我不确定这个解决方案是否好。当进程通过正在运行的作业自行终止时,我会遇到哪些潜在问题?

【问题讨论】:

  • 好的。我想你最好在你的 worker() 中处理超时并将结果写入一个公共集合。这样,你只需要在所有线程上调用join(),然后处理结果。如果您的系统负载不重,则一切正常。

标签: python multithreading multiprocessing python-multithreading python-multiprocessing


【解决方案1】:

停止正在运行的作业没有隐含的风险,操作系统将负责正确终止进程。

如果您的工作是写入文件,您的磁盘上可能会出现大量截断的文件。

如果您在 DB 上写入或连接到某个远程进程,也可能会出现一些小问题。

不过,Python 标准 Pool 不支持在任务超时时终止工作线程。突然终止进程可能会导致您的应用程序出现奇怪的行为。

Pebble processing Pool 确实支持超时任务。

from pebble import process, TimeoutError

with process.Pool() as pool:
    task = pool.schedule(function, args=[1,2], timeout=5)

    try:
        result = task.get()
    except TimeoutError:
        print "Task: %s took more than 5 seconds to complete" % task

【讨论】:

  • 看起来不错。您现在有在生产中使用它的成功案例吗?
  • 不确定我理解正确。您想要 Pebble 在生产或系统杀戮过程中的成功案例吗? Pebble 是一个相当稳定的库,有一个公平的amount of downloads。
  • 是的,你理解正确。你知道使用peeble的项目吗?
  • 我们在少数系统的生产环境中使用 Pebble,它运行良好。我不知道有任何公共项目使用它。
猜你喜欢
  • 1970-01-01
  • 2021-07-24
  • 2020-08-14
  • 2016-11-10
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
相关资源
最近更新 更多