Home > Software engineering >  How to Avoid Running a New Thread If a Thread Already Exists
How to Avoid Running a New Thread If a Thread Already Exists

Time:07-18

I need to run an X thread once and stop spawning new threads if X thread is still running. For example, assume my thread is initiated from within a function called 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.

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(). In other words, whenever we call start_my_thread(), I want to check do we have an existing running kline_thread thread or not. If we don't, trigger kline_thread.start(). If we already have kline_thread running, don't trigger kline_thread.start().

I'm using Python3.x. Any help will be appreciated.

CodePudding user response:

You can use threading.enumerate() function, as described in the doc :

Return a list of all Thread objects currently active. The list includes daemonic threads and dummy thread objects created by 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

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
  • Related