简体   繁体   English

Python:同时结束多个函数

[英]Python: Ending multiple functions simultaneously

After looking at Python: Executing multiple functions simultaneously , I can successfully make two functions run simultaneously.看了Python: Executing multiple functions simultaneously后,我可以成功让两个函数同时运行。

Is it possible to make two functions terminate simultaneously?是否可以让两个函数同时终止?

That is, given the following code:也就是说,给定以下代码:

from multiprocessing import Process

def func1:
     while True:
          # does something and breaks based on key-pressed condition

def func2:
     while True:
          # does something

if __name__=='__main__':
     p1 = Process(target = func1)
     p1.start()
     p2 = Process(target = func2)
     p2.start()

Can I make func2 terminate immediately after func1 finishes (upon the key-pressed condition being satisfied)?我可以让 func2 在 func1 完成后立即终止吗(在满足按键条件时)?

Thanks in advance!提前致谢!

You can wait for p1 to finish with p1.join then terminate p2.您可以等待 p1 完成 p1.join 然后终止 p2。

p1 = Process(target = func1)
p2 = Process(target = func2)
p1.start()
p2.start()

p1.join()
p2.terminate()
p2.join()

One possible solution is to share a flag between the two processes:一种可能的解决方案是在两个进程之间共享一个标志:

An example:一个例子:

from multiprocessing import Process, Value
import time


def func1(flag):
    while flag.value:
        print("process1")
        time.sleep(1)


def func2(flag):
    cnt = 0

    while flag.value:
        print("process2")
        cnt += 1
        if cnt == 10:
            flag.value = False

        time.sleep(1)


if __name__ == '__main__':
    run = Value('f', True)

    p1 = Process(target=func1, args=(run,))
    p1.start()
    p2 = Process(target=func2, args=(run,))
    p2.start()
    p1.join()
    p2.join()

Notice that the second process sets the common flag to false after ten iterations, which also makes the process 1 stop.请注意,第二个进程在十次迭代后将 common 标志设置为 false,这也使进程 1 停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM