程序立即终止忽略时间。睡眠()在守护进程线程中

2024-03-29 05:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类正在调用下面这样的线程。你知道吗

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语句,它也不打印。这里有什么问题?你知道吗

此代码应完整且可复制


Tags: runimportselftruetimedefsleep语句
1条回答
网友
1楼 · 发布于 2024-03-29 05:54:47

问题是这条线:

thread.daemon = True

threading documentation

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

因为您已经将线程设置为守护进程线程,所以python不会在退出程序之前等待它完成。一旦主线程执行完您的代码,守护进程线程就会被终止,程序就会退出。你知道吗

解决这个问题有两种方法:

  1. 删除thread.daemon = True赋值,以便python等待线程退出。你知道吗
  2. 通过调用^{}显式地等待线程完成。你知道吗

相关问题 更多 >