Python线程挂起
似乎每当我尝试启动一个后台线程时,在线程完成之前,你永远都不会看到它下面的代码。这是Python 3.6.5 我在一个更复杂的应用程序中遇到了这个问题,但它似乎与多处理或子流程无关 以下代码从不打印“FG works”:Python线程挂起,python,multithreading,freeze,Python,Multithreading,Freeze,似乎每当我尝试启动一个后台线程时,在线程完成之前,你永远都不会看到它下面的代码。这是Python 3.6.5 我在一个更复杂的应用程序中遇到了这个问题,但它似乎与多处理或子流程无关 以下代码从不打印“FG works”: import sys import time import threading def bgthread(): while True: print('BG works') sys.stdout.flush() time.
import sys
import time
import threading
def bgthread():
while True:
print('BG works')
sys.stdout.flush()
time.sleep(1)
threading.Thread(bgthread()).start()
while True:
print('FG works')
sys.stdout.flush()
time.sleep(1)
如果有人看到我的明显错误,请插话。您不想在启动新线程时调用该函数,因为这将阻止主线程。你应该这样做
threading.Thread(target=bgthread).start()
这是因为对
线程
初始值设定项的调用正在调用bgthread
,而不是引用它以便以后启动。您不希望在启动新线程时调用该函数,因为这将阻塞主线程。你应该这样做
threading.Thread(target=bgthread).start()
这是因为对线程
初始值设定项的调用是调用bgthread
,而不是引用它以便以后启动