【问题标题】:How can I join the 2nd process which has exited while 1st process is still running?如何在第一个进程仍在运行时加入已退出的第二个进程?
【发布时间】:2017-06-11 14:51:20
【问题描述】:

部分代码:

p1 = Process(target1, args1)
p2 = Process(target2, args2)

p1.start()
p2.start()

p1.join()
p2.join()

任何进程都有可能被中断;因此我不应该按顺序加入,因为加入是一个阻塞调用。

请帮忙。

【问题讨论】:

    标签: python-2.7 python-multiprocessing


    【解决方案1】:

    这取决于您的意图 - 当您想要等待所选进程完成时使用Process.join()(因此它“加入”回主进程),但您始终可以在循环中检查您的进程状态在第二个完成之前等待一个完成。

    我建议使用multiprocessing.Event 并将其传递给您的进程,然后您的进程可以在退出时设置标志,您可以在主进程中执行事件循环等待该事件以确保进程退出.您还可以使用相同的系统来命令您的进程退出。

    如果您只想确定进程何时结束而不等待前一个进程,您还可以将timeout 设置为Process.join() 来循环访问进程,例如:

    import multiprocessing
    import time
    
    def target(name, timeout=5):
        print("{} started...".format(name))
        time.sleep(timeout)
        print("{} finishing...".format(name))
    
    # define a process list for convenience with initialization/shutdown:
    processes = {
        "P1": {"target": target, "args": ["P1", 5]},
        "P2": {"target": target, "args": ["P2", 3]},
        "P3": {"target": target, "args": ["P3", 8]},
        "P4": {"target": target, "args": ["P4", 1]},
    }
    
    if __name__ == "__main__":   # cross-platform multiprocessing guard
        # initialize and start our processes:
        for name, kwargs in processes.items():  # loop through the process list
            print("Initializing: {}...".format(name))
            processes[name] = multiprocessing.Process(**kwargs)
            print("Starting: {}...".format(name))
            processes[name].start()
    
        # when its time to exit...
        processes = processes.items()  # easier to manage as a list of tuples
        while processes:  # loop for as long as we have alive processes...
            name, process = processes.pop(0)  # remove the first element from our process list
            process.join(0.1)  # trying to join the current process, wait for 100ms
            if process.is_alive():  # Process still alive, moving to the next one...
                processes.append((name, process))  # add it to the back of the queue
            else:
                print("{} ended!".format(name))
        print("Woo-hoo! All processes exited...")
    

    注意:在这种情况下,这不会要求将您的子进程“加入”到主进程,但如果您的子进程等待任务而不调用 join(本质上是wait()),它将永远不会关闭。但是,这也是您在第一种情况下要使用 multiprocessing.Event 的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 2020-01-24
      • 2016-03-21
      • 2011-07-04
      • 2015-01-30
      相关资源
      最近更新 更多