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

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

How to exit a function from another function?

问题

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

我想做类似这样的事情:

  1. def A():
  2. while True:
  3. if condition is True:
  4. #做一些事情
  5. else:
  6. pass
  7. def B():
  8. while True:
  9. if condition is True:
  10. #停止A()函数
  11. break
  12. else:
  13. pass
  14. def main():
  15. p1 = multiprocessing.Process(target=A)
  16. p2 = multiprocessing.Process(target=B)
  17. p1.start()
  18. p2.start()
  19. p1.join()
  20. p2.join()
  21. if __name__ == '__main__':
  22. 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:

  1. def A():
  2. while True:
  3. if condition is True:
  4. #do something
  5. else:
  6. True
  7. def B():
  8. while True:
  9. if condition is True:
  10. #stop A() function
  11. else:
  12. True
  13. def main():
  14. p1 = multiprocessing.Process(target=A())
  15. p2 = multiprocessing.Process(target=B())
  16. p1.start()
  17. p2.start()
  18. p1.join()
  19. p2.join()
  20. if __name__ == '__main__':
  21. main()

答案1

得分: 1

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

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

  1. while not predicate():
  2. 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

  1. while not predicate():
  2. 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:

确定