【问题标题】:Multithreading in Python without using time.sleep at the end?Python 中的多线程,最后不使用 time.sleep?
【发布时间】:2016-04-09 02:53:09
【问题描述】:

所以我正在尝试使用我在网上找到的这个 sn-p 在后台运行一些代码。然而,我的主要问题是我试图让它在最后不使用 time.sleep(3) 的情况下工作,而且似乎无法弄清楚。有什么建议?为什么它最后只与 time.sleep(n) 一起工作?

import threading
import time


class ThreadingExample(object):
    """ Threading example class
    The run() method will be started and it will run in the background
    until the application exits.
    """

    def __init__(self, interval=1):
        """ Constructor
        :type interval: int
        :param interval: Check interval, in seconds
        """
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        while True:
            # Do something
            print('Doing something imporant in the background')

            time.sleep(self.interval)

example = ThreadingExample()
time.sleep(3)
print('Done')

【问题讨论】:

标签: python multithreading python-multithreading


【解决方案1】:

当 python 退出时,所有的守护线程都被杀死。如果过早退出,执行重要后台工作的线程将在实际运行之前被杀死。

现在您的后台作业使用while True;也许你想用一些实际的退出条件替换它,并在退出之前加入线程。

【讨论】:

    【解决方案2】:

    你看到这条线

    thread.daemon = True                            # Daemonize thread
    

    这意味着程序结束时您的线程将退出(主线程)。如果你不放一个

    time.sleep(3)
    

    您的程序将退出如此之快,以至于线程很可能在退出之前什么都不做......

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2019-11-22
      • 1970-01-01
      • 2017-06-29
      • 1970-01-01
      • 2020-07-23
      相关资源
      最近更新 更多