【问题标题】:main thread not execute until child thread finished主线程直到子线程完成才执行
【发布时间】:2021-05-23 23:43:45
【问题描述】:

基本上,我有一个程序,我想在其中创建一个线程来执行主线程旁边的某些功能。但是在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")

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

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

【问题讨论】:

  • wt.join() 明确等待wt 结束。主线程 正在 并行执行,但它正在执行您告诉它执行的操作:等待 wt 结束。将wt.join() 下移一行,主线程将立即打印"do other stuff ..."

标签: python multithreading


【解决方案1】:

调用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')

【讨论】:

  • 这基本上就是 Tim Peters 所说的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多