我有一个类正在调用下面这样的线程。你知道吗
import threading
import time
class ThreadingExample:
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
# Do something
print('Doing something important in the background')
time.sleep(100)
# a print statement will not be executed here even with flush=True
example = ThreadingExample()
但是,sleep
不起作用。线程是从run()中的第一个print开始执行的,但是程序在print语句之后立即终止。你知道吗
出于测试目的,我在sleep(100)之后插入了另一个print语句,它也不打印。这里有什么问题?你知道吗
此代码应完整且可复制
问题是这条线:
从threading documentation:
因为您已经将线程设置为守护进程线程,所以python不会在退出程序之前等待它完成。一旦主线程执行完您的代码,守护进程线程就会被终止,程序就会退出。你知道吗
解决这个问题有两种方法:
thread.daemon = True
赋值,以便python等待线程退出。你知道吗相关问题 更多 >
编程相关推荐