简体   繁体   中英

How do I start a thread only if the thread is not running for python

I am trying to start create a thread to run a process (task function), but only creating the thread if the thread is not already running, and run only once. The main.py will be refreshed regularly and trigger the thread process to run in the background. This is so that I can save on compute resources. For example, if users refresh my page 3 times, the process goes on to run 3 threads, but I am trying to do so it only run once within the 10 seconds(during sleep). I just need the first time to work and trigger the thread/task and ignore subsequent triggers. I have created a script that I think should be working but it runs tasks every time main() runs, when it shouldn't.

I have created a try except to check if the current_thread is existing, if it is existing to check if its not running with the 'is_alive()' method, and if not to ignore(and not proceed) if it exists and still "is_alive()". If the exception triggers, the current_thread does not exist and the script proceeds to start a new thread (current_thread). Based on the logic in the script, It looks like current_thread.is_alive() is not working since I have a thread running but its still triggering new current_thread.start().

import time
import threading

def task():
    print ('start task')
    time.sleep(10)
    print ('task complete')

current_thread = threading.Thread(target=task)

def main():

    try:
        if not current_thread.is_alive():
            current_thread.start()
            current_thread.join()
    except UnboundLocalError as e:
        current_thread.start()
        current_thread.join()
if __name__ == '__main__':
    main()

While I found a answer that is related (it only runs a new thread when the old one finishes running), the script is not very useful since it runs infinitely, while I only want the thread to run one time. python - start a thread if it's not already running .

Any help on what I am missing or what can be done to fix this is appreciated.

Just use a boolean variable to keep track of whether or not you've started the thread.

import time
import threading

def task():
    print ('start task')
    time.sleep(10)
    print ('task complete')

def main():
    current_thread = threading.Thread(target=task)
    started = False
    for _ in range(12):
        if not started:
            started = True
            current_thread.start()
        time.sleep(1.0)
        print("Main loop...")
        
if __name__ == '__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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