简体   繁体   English

如果线程已经存在,如何避免运行新线程

[英]How to Avoid Running a New Thread If a Thread Already Exists

I need to run an X thread once and stop spawning new threads if X thread is still running.如果 X 线程仍在运行,我需要运行一次 X 线程并停止生成新线程。 For example, assume my thread is initiated from within a function called start_my_thread().例如,假设我的线程是从一个名为 start_my_thread() 的函数中启动的。

start_my_thread() initiates a thread for kline_func, which listens from a remote server and runs indefinitely assuming no network interruption happens. start_my_thread() 为 kline_func 启动一个线程,该线程从远程服务器侦听并无限期运行,假设没有发生网络中断。

def kline_func():
    ...
    ...
    ...

    while True:
       pass

def start_my_thread():
    kline_thread = Thread(target = kline_func)
    kline_thread.start()

start_my_thread() # first call
start_my_thread() # second call
start_my_thread() # third call

My question is how do I make sure kline_thread.start() is called once only no matter how many times I call start_my_thread().我的问题是,无论我调用 start_my_thread() 多少次,如何确保只调用一次 kline_thread.start()。 In other words, whenever we call start_my_thread(), I want to check do we have an existing running kline_thread thread or not.换句话说,每当我们调用 start_my_thread() 时,我想检查我们是否有一个现有的正在运行的 kline_thread 线程。 If we don't, trigger kline_thread.start().如果我们不这样做,则触发 kline_thread.start()。 If we already have kline_thread running, don't trigger kline_thread.start().如果我们已经运行了 kline_thread,则不要触发 kline_thread.start()。

I'm using Python3.x.我正在使用 Python3.x。 Any help will be appreciated.任何帮助将不胜感激。

You can use threading.enumerate() function, as described in the doc :您可以使用threading.enumerate()函数,如文档中所述:

Return a list of all Thread objects currently active.返回当前活动的所有 Thread 对象的列表。 The list includes daemonic threads and dummy thread objects created by current_thread().该列表包括由 current_thread() 创建的守护线程和虚拟线程对象。 It excludes terminated threads and threads that have not yet been started.它不包括已终止的线程和尚未启动的线程。 However, the main thread is always part of the result, even when terminated但是,主线程始终是结果的一部分,即使在终止时也是如此

We set the thread name when initializing the Thread object我们在初始化Thread对象的时候设置了线程名

def kline_func():
    ...
    ...
    ...

    while True:
       pass

def start_my_thread():

    thread_names = [t.name for t in threading.enumerate()]
 
    if "kline_thread" not in thread_names:
        kline_thread = Thread(target = kline_func, name="kline_thread")
        kline_thread.start()


start_my_thread() # first call
start_my_thread() # second call
start_my_thread() # third call

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM