python - 如何在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
解决方案
没有一个真实的例子很难做到。所以我试着用你的伪代码来解释我的想法。我将使用全局 _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时,可以迭代
推荐阅读
- angular - 在异步中使用 Promise 时捕获 HTML5 FileReader 的结果
- javascript - 获取 beforeEach 以仅在它所在的文件中运行测试
- google-apps-script - Google Apps 脚本中对话窗口中的动态文本框
- ifc - BimServer 1.4 getModel 总是返回一个空模型
- node.js - Firebase Admin FCM 发送消息不起作用
- python - 用于python 3的国家仪器pyDAQmx
- matlab - 修改 x 轴标注 (Matlab)
- c# - 带有接口类型键的字典,获取实现接口的键
- android - 正在调用 getResources().getString(
, params) 内部循环会降低性能 - python-3.x - 最佳回报概率风险计算