繁体   English   中英

主线程在子线程完成之前不会执行

[英]main thread not execute until child thread finished

基本上,我有一个程序,我想在其中创建一个线程来执行主线程旁边的某些 function。 但是在 python 中,似乎当我创建线程时,直到创建线程尚未完成,执行才不会传递给主线程。

请参见以下示例:

import threading
import time


def testing():
    time.sleep(30)


wt = threading.Thread(target=testing, name="test", daemon=True)
print("Starting thread")
wt.start()
wt.join()
print("do other stuff next to above thread")

如果你运行上面的程序,直到测试 function 没有完成,主程序不会打印do other stuff next to above thread

不确定我是否缺少某些参数或什么,但有人可以告诉我如何创建一个让主程序继续执行的线程吗?

调用wt.join()使脚本停止并等待 wt 完成。 如果您想在 wt 运行时运行其他东西,请稍后再调用wt.join()

试试这段代码看看:

import threading
import time

def testing():
    print('in testing()')
    time.sleep(5)

wt = threading.Thread(target=testing, name="test", daemon=True)
print("Starting thread")
wt.start()
print("do other stuff next to above thread")
wt.join()
print('after everything')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM