如何从另一个函数中退出一个函数?

huangapple go评论111阅读模式
英文:

How to exit a function from another function?

问题

要在另一个函数中的语句为真时退出函数。我正在使用多进程,所以它们同时运行。

我想做类似这样的事情:

def A():
    while True:
        if condition is True:
            #做一些事情
        else:
            pass

def B():
    while True:
        if condition is True:
            #停止A()函数
            break
        else:
            pass

def main():
    p1 = multiprocessing.Process(target=A)
    p2 = multiprocessing.Process(target=B)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

if __name__ == '__main__':
    main()
英文:

I want to exit a function in another function if statement is True. I am using multiprocessing so they are running concurrently.

I want to make something like this:

def A():
    while True:
        if condition is True:
            #do something
        else:
            True

def B():
    while True:
        if condition is True:
            #stop A() function
        else:
            True

def main():
    p1 = multiprocessing.Process(target=A())
    p2 = multiprocessing.Process(target=B())
    p1.start()
    p2.start()
    p1.join()
    p2.join()

if __name__ == '__main__':
    main()

答案1

得分: 1

有多个同步原语可供使用,例如条件变量:

你可以使用 mp.Condition() 进行调用:

while not predicate():
    cv.wait()

A() 中,以及在 B() 中使用 notify()

英文:

There are multiple synchronization primitives you could use, such as a condition variable:

You could use a mp.Condition() calling

while not predicate():
    cv.wait()

in A() and notify() in B()

huangapple
  • 本文由 发表于 2023年3月7日 22:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定