运行 只有一个线程实例

Run only one Instance of a Thread

我是 Python 的新手,对线程有疑问。

我有一个经常调用的函数。此函数在新线程中启动另一个函数。

def calledOften(id):
    t = threading.Thread(target=doit, args=(id))
    t.start()    

def doit(arg):
    while true:
    #Long running function that is using arg

When calledOften 每次创建新线程时都会调用。我的目标是始终终止最后一个 运行 线程 --> 始终应该只有一个 运行 doit() 函数。

我尝试了什么: How to stop a looping thread in Python?

def calledOften(id):
    t = threading.Thread(target=doit, args=(id,))
    t.start()
    time.sleep(5)
    t.do_run = False

这段代码(带有修改后的 doit 函数)让我在 5 秒后停止线程。 但是在开始新线程之前我不能调用 t.do_run = False...这很明显,因为它没有定义...

有人知道如何停止最后一个 运行 线程并启动一个新线程吗?

谢谢 ;)

我想你可以自己决定何时从线程内部终止线程的执行。那不应该给您带来任何问题。您可以想到线程管理器方法 - 如下所示

import threading


class DoIt(threading.Thread):
    def __init__(self, id, stop_flag):
        super().__init__()

        self.id = id
        self.stop_flag = stop_flag

    def run(self):
        while not self.stop_flag():
            pass  # do something


class CalledOftenManager:
    __stop_run = False
    __instance = None

    def _stop_flag(self):
        return CalledOftenManager.__stop_run

    def calledOften(self, id):
        if CalledOftenManager.__instance is not None:
            CalledOftenManager.__stop_run = True
            while CalledOftenManager.__instance.isAlive():
                pass  # wait for the thread to terminate

            CalledOftenManager.__stop_run = False
            CalledOftenManager.__instance = DoIt(id, CalledOftenManager._stop_flag)
            CalledOftenManager.__instance.start()


# Call Manager always
CalledOftenManager.calledOften(1)
CalledOftenManager.calledOften(2)
CalledOftenManager.calledOften(3)

现在,我在这里尝试的是制作一个控制器来调用线程DoIt。它是实现您需要的一种方法。