python - 如何在 func1 继续运行和返回时在 func1 中调用 func2?
问题描述
代码示例:
def func2(paraI):
time.sleep(10)
print('awaked, i=%d'%paraI)
def func1():
i = 5
# func2 will use parameter inside func1
# but func1 doesn't depend on func2
# so func2 is expected to run another thread
# and func1 will keep running (return)
func2(i)
return i
if __name__=='__main__':
print(func1())
我想5
立即输出,并在 10s 后awaked, i=5
打印,而不是被阻止 10s then awaked, i=5 5
。
如何在 Python3 中实现这一点?谢谢。
解决方案
在 Python 中使用线程模块:
thread = threading.Thread(target = func2, args = (i, ))
thread.start()
尝试这个:
import threading
import time
def func2(paraI):
time.sleep(10)
print('awaked, i = %d' % paraI)
def func1():
i = 5
# func2 will use parameter inside func1
# but func1 doesn't depend on func2
# so func2 is expected to run another thread
# and func1 will keep running (return)
print("Starting the Thread")
thread = threading.Thread(target = func2, args = (i,))
thread.start()
return i
if __name__ == "__main__":
print("Func1 returned", func1())
输出:
Starting the Thread
Func1 returned 5
几秒钟后10
,...
awaked, i = 5
推荐阅读
- python - 如何将行插入数据框
- firebase - Flutter FutureBuilder 什么都不返回 - Cloud Firestore 和反序列化
- angular - 为什么将返回类型方法的输出分配给变量时,Typescript 无法推断类型?
- c# - 如何在程序启动时通过视图模型将视图注入区域
- oracle - 如何在 Oracle 中设置 UTF8 编码?
- python - 使用 Python 跟踪 HTML 或 PHP 重定向?
- rest - 分布式系统中 REST API 的幂等性和竞争条件
- c# - 不可信数据的反序列化
- r - 用字符串数组管道 image_annotate
- python - 为索引范围内的每个项目制作 n 长度子列表