gpt4 book ai didi

python - Python 可停止线程是否需要守护进程或 .join()?

转载 作者:行者123 更新时间:2023-12-04 18:43:57 29 4
gpt4 key购买 nike

使用类时Pup用于创建在后台运行的可停止线程,直到 .stop()叫做:

  • pup.join() 时会发生什么在 pup.stop() 之后不调用?以下是否会导致泄漏:
    pup = Pup()
    pup.start()
    time.sleep(5)
    pup.stop()

    pup2 = Pup()
    pup2.start()
    time.sleep(5)
    pup2.stop()

    pup3 = Pup()
    pup3.start()
    time.sleep(5)
    pup3.stop()
  • 必须 pup是一个守护线程,因为我们在后台运行它?

  • 下面的主要代码是从 this SO answer借来的
    import time
    import threading

    class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
    super(StoppableThread, self).__init__(*args, **kwargs)
    self._stopper = threading.Event()

    def stop(self):
    self._stopper.set()

    def stopped(self):
    return self._stopper.isSet()


    class Pup(StoppableThread):
    def __init__(self, i, *args, **kwargs):
    super(Pup, self).__init__(*args, **kwargs)
    self.i = i

    def run(self):
    while True:
    if self.stopped():
    return
    print("Hello, world!", i)
    time.sleep(1)

    for i in range(100):
    pup = Pup(i)
    pup.start()
    time.sleep(5)
    pup.stop()

    最佳答案

    StoppableThread应该是 join编。
    因为它只是一个关于 threading.Thread 的薄包装让您可以设置和检查标志 stopper .
    在这种情况下,必须有一个代码定期检查这个标志。检查之间的延迟量取决于类的用户。
    并且假设线程应该正确停止,您必须使用 join .因为如果你把线程设为 daemon并尝试在应用程序完成之前停止它:

    Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.


  • 仅当您的代码负责检查 stopper 时,才可能发生泄漏。标志和随后退出线程无法正常工作。否则,没有泄漏,因为应用程序,甚至join未被调用,将等待所有非守护线程完成。但是使用 join将对程序流程提供更多控制。
  • 考虑到以上所有因素,我认为制作 StoppableThreaddaemon是个坏主意。
  • 关于python - Python 可停止线程是否需要守护进程或 .join()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62689369/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com