Python线程挂起

时间:2018-05-31 18:08:51

标签: python multithreading hang

似乎任何时候我尝试启动后台线程,在线程完成之前,你永远不会在它下面找到代码。这是Python 3.6.5

我遇到了一个更复杂的应用程序的问题,但它似乎与多处理或子进程无关。

以下代码从不打印'FG作品':

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)

如果有人看到我明显的错误,请加入。

1 个答案:

答案 0 :(得分:4)

启动新线程时不想调用该函数,因为这会阻塞主线程。你应该这样做,

threading.Thread(target=bgthread).start()

这是因为对Thread初始化程序的调用正在调用bgthread而不是引用它以便稍后启动。