仅运行一个线程的实例

问题描述 投票:0回答:1

我对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

每次创建新线程时都会调用namedOften时。我的目标是始终终止最后一个正在运行的线程->在任何时候都应该只有一个正在运行的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。这很明显,因为它没有定义...

有人知道如何停止上一个正在运行的线程并启动一个新线程吗?

谢谢;)

python python-multithreading
1个回答
0
投票

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

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的控制器。它是实现您所需的一种方法。

© www.soinside.com 2019 - 2024. All rights reserved.