我正在尝试在python中运行线程,但它还很新。在学习基础知识时,当我启动线程时,该程序不会与主程序一起继续,而是停留在线程中。即,它仅打印“ hello world”,而从不打印“ hi there”。
from threading import Thread
import time
def hello_world():
while True:
print("hello world")
time.sleep(5)
t = Thread(target = hello_world())
t.start()
print("hi there")
我正在使用spyder IDE。
我在网上搜索了一些基本的线程程序,但是对于这些程序,代码是有效的。
我应该如何进行?
答案 0 :(得分:1)
您的问题在t = Thread(target = hello_world())
行中。
您正在尝试使用Thread
参数创建一个target
。根据评估顺序,Python首先需要知道要分配给target
的内容,因此它评估了RHS。在您的情况下,RHS为hello_world()
。因此该函数已经在那个确切的时刻被调用了!
因此函数执行并进入无限循环,并且Thread
甚至都不会被创建,并且程序会卡住。
您想要做的就是仅向该函数传递引用给target
,因此将上述行更改为:
t = Thread(target = hello_world)
现在,RHS被评估为对给定函数的引用,并且在幕后将创建Thread
,对该函数进行调用,并且主线程将按预期运行。