python - 在dtor python上加入线程

标签 python multithreading python-multithreading

我创建了一个在ctor(__init__)中启动新线程的类
并在dtor(__del__)中加入了线程
像这样:

import threading
import time


class Dthread:
    m_thread: threading.Thread

    def __init__(self, interval=1):
        self.interval = interval
        self.m_thread = threading.Thread(target=self.run, args=())
        self.m_thread.daemon = True
        self.m_thread.start()

    def __del__(self):
        self.m_thread.join()

    def run(self):
        while True:
            print('Doing something important in the background')
            time.sleep(self.interval)


g = Dthread(True)
print('Checkpoint')
print('Bye')

我在“main function”启动后要继续运行的线程是什么,但是当我在IDE中运行此代码时,我得到了:
Doing something important in the background 
Checkpoint
Bye 
当我在repl.it中运行它时
我得到:
Doing something important in the background 
Checkpoint
Bye
Doing something important in the background 
Doing something important in the background 
Doing something important in the background ... 

最佳答案

如果从命令行运行,则程序将按预期运行。因此,我猜测您是在IDE或jupyter笔记本或类似的东西中运行的,没有真正的退出处理发生,因此守护进程线程被终止。我已经对该程序进行了修改,使其具有一个单独的Runner类,其中包含重要的代码。它将检查stop条件,并在其run方法中终止其循环,以便实际上可以连接线程(您在原始代码中拥有的join调用实际上对于多余的守护进程线程是多余的,当存在非非守护程序线程离开,并且由于run方法永不返回而将永远无法完成)。
Runner类需要与Dthread类分开,Dthread类的析构函数调用Runner类的stop方法,然后加入线程。这是因为我发现当线程在当前正在运行析构函数的同一实例上运行方法时,它不起作用。注意,我还通过将实例设置为Dthread并强制进行垃圾回收来确保调用None实例的析构函数。当然,您可以直接在join实例上直接调用Dthread方法。

import threading
import time
import gc

class Dthread:
    m_thread: threading.Thread

    class Runner():
        def __init__(self, interval):
            self._interval = interval
            self._stop = False

        def run(self):
            while not self._stop:
                print('Doing something important in the background')
                time.sleep(self._interval)

        def stop(self):
            self._stop = True



    def __init__(self, interval=1):
        self.stop = False
        self.joined = False
        self.runner = Dthread.Runner(interval)
        self.m_thread = threading.Thread(target=self.runner.run, args=())
        #self.m_thread.daemon = True
        self.m_thread.start()

    def __del__(self):
        print('dtor called.')
        self.join()

    def join(self):
        if not self.joined:
            self.runner.stop()
            self.m_thread.join()
            self.joined = True


g = Dthread(1.0)
print('Checkpoint')
print('Bye')
g = None # or g.join()
gc.collect()

关于python - 在dtor python上加入线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662967/

相关文章:

python - 如何将 CNN 从 keras 转换为 mxnet?

python - 什么是IndexError?我不断得到它

python - 短路列表理解

java - 我的绘图线程突然停止的原因是什么?

python - 在Python中传递锁

python - 从 PIL.Image 获取二进制图像数据?

ios - requiresMainQueueSetup 和 dispatch_get_main_queue 的区别?

c# - 在单声道 3.2.8 Ubuntu Server 14 上使用 HttpWebRequest

python - 最大线程限制实际上是 Python/Linux 的不相关问题吗?

Python多线程写日志