首页 > 解决方案 > 如何在while循环中等待函数完成?

问题描述

我的代码的简化结构如下。我正在从 while 循环内部调用一个函数,但是在该函数内部调用 form 的函数需要在 while 循环的下一次迭代之前完成。我已经尝试过如下线程,但它会给我RuntimeError: main thread is not in main loop.

什么是解决这个问题的好方法?

def mainFunction():
   #some code

def secondFunction():
   #some code
   mainFunction()

def thirdfunction():
   #some code
   def funcInFunc():
      #some code 
      secondFunction()

def fourthFunction():
   #some code
   while [condition]:
      #some code
      #here calling funcInFunc() inside thirdFunction()
      funcInFunc()
      #need to wait for mainFunction() called from secondFunction() called from funcInFunc() to 
finish before next iteration of this while loop 
 
      #WAIT FOR mainFunction() TO FINISH
      #Tried but didn't work:
      t = threading.Thread(target=funcInFunc, args=())   
      t.start()
      while t_isAlive():
         pass

标签: pythonpython-multithreading

解决方案


没有一个真实的例子很难做到。所以我试着用你的伪代码来解释我的想法。我将使用全局 _flag 变量来授权线程的以下内容。

def mainFunction():
   #some code
   # end of mainFunction
   _flag = 0

def secondFunction():
   #some code
   mainFunction()

def thirdfunction():
   #some code
   def funcInFunc():
      #some code
      _flag = 1
      secondFunction()

def fourthFunction():
   #some code
   while [condition]:
      #some code
      #here calling funcInFunc() inside thirdFunction()
      funcInFunc()
      #need to wait for mainFunction() called from secondFunction() called from        funcInFunc() to finish before next iteration of this while loop
      if _flag == 1 
 
      #WAIT FOR mainFunction() TO FINISH
      if _flag == 0

不要忘记在有用的地方声明它是全局的。当_flag == 1时,它可以继续。当_flag == 0时,可以迭代


推荐阅读