首页 > 解决方案 > 如何在 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 中实现这一点?谢谢。

标签: pythonpython-3.xmultithreadingprocessmultiprocessing

解决方案


在 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

推荐阅读