python - 在 python 中使用多处理创建的进程上使用 join()

标签 python parallel-processing multiprocessing

我正在使用 multiprocessing 模块的 Process 类来生成多个进程,这些进程执行一些脚本然后死掉。我想要的是,在每个进程上应用超时,这样如果不能及时执行,进程就会死掉 超时。我在 Process 对象上使用 join(timeout)由于 join() 函数不会终止进程,它只是阻塞进程直到它完成

现在我的问题是:将 join()timeout 一起使用是否有任何副作用......比如,在主进程结束后,进程会自动清理吗??或者我必须手动终止这些进程??

我是 python 及其多处理模块的新手,请耐心等待。


我的代码,它在 for 循环中创建进程::

q = Queue()
jobs = [
        Process(
            target=get_current_value,
            args=(q,),
            kwargs=
            {
                'device': device,
                'service_list': service_list,
                'data_source_list': data_source_list
                }
            ) for device in device_list
        ]
for j in jobs:
        j.start()
for k in jobs:
        k.join()

最佳答案

timeout 参数只是告诉 join 等待 Process 退出的时间然后放弃。如果 timeout 到期,Process 不会退出; join 调用只是解除阻塞。如果您想在超时到期时结束您的工作人员,您需要手动执行此操作。您可以按照 wRAR 的建议使用 terminate 来不干净地关闭东西,或者使用其他一些信号机制来告诉 child 干净地关闭:

p = Process(target=worker, args=(queue,))
p.start()
p.join(50)
if p.isalive(): # join timed out without the process actually finishing
    #p.terminate() # unclean shutdown

如果您不想使用terminate,替代方法实际上取决于工作人员在做什么。如果他们从队列中消费,您可以使用哨兵:

def worker(queue):
   for item in iter(queue.get, None): # None will break the loop
       # Do normal work

if __name__ == "__main__":
    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target=worker, args=(queue,))
    p.start()
    # Do normal work here

    # Time to shut down
    queue.put(None)

或者你可以使用一个Event,如果你在一个循环中做一些其他的操作:

def worker(event):
   while not event.is_set():
       # Do work here

if __name__ == "__main__":
    event= multiprocessing.Event()
    p = multiprocessing.Process(target=worker, args=(event,))
    p.start()
    # Do normal work here

    # Time to shut down
    event.set()

不过,使用 terminate 可能会很好,除非您的子进程使用的资源在进程意外关闭时可能会损坏(例如写入文件或数据库,或持有锁).如果您只是在 worker 中进行一些计算,使用 terminate 不会造成任何伤害。

关于python - 在 python 中使用多处理创建的进程上使用 join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25638231/

相关文章:

python多处理特有的内存管理

Python 单元测试和何时模拟

python - 导入对日志记录的副作用 : how to reset the logging module?

python - 将表示为嵌套dicts的几个 "Response"对象转换为python中的多维列表

c# - Parallel.For 循环卡住

c - 如何使用 Pthreads 并行化我的 n 皇后拼图?

python - 使用 pyenv,我如何 pip 安装全局 CLI 并使它们即使在 virtualenv 中也可用?

c - MPI 反向探针

python - 如何将 pyautogui 连接到虚拟显示器?

python 3 : Shared Array with strings between processes