简体   繁体   中英

How to make sure that only one instance of a thread is running in Python?

I have a program with three threads. I call them like this:

if __name__ == "__main__":
    while True:
        try:
            t1().start()
        except:
            log.debug('Trouble with t1 synchronizer')
        try:
            t2().start()
        except:
            log.debug('Trouble with t2 synchronizer')
        try:
            t3().start()
        except:
            log.debug('Trouble with t3 synchronizer')

I want to keep these 3 threads running all the time. But I also want to make sure that only one instance each of t1, t2 and t3 is running at a time.

EDIT

The only solution I can think of is having lock files in each threads. Somthing like

if os.path.exists(lockfile):
   EXIT THREAD
f=open(lockfile,'w')
f.write('lock')
f.close()
THREAD_STUFF
os.remove(lockfile)

But somehow it does not look like a clean solution to me as the program might have exited because of some reason and the threads may not launch at all.

You are correct one way to make sure that the threads are only running once each would be with a lock file.

How ever there is another way to check if they are running instead of continuously trying to run them. By using the following code

if __name__ == "__main__":
    try:
        t1().start()
    except:
        log.debug('Trouble with t1 synchronizer')
    try:
        t2().start()
    except:
        log.debug('Trouble with t2 synchronizer')
    try:
        t3().start()
    except:
        log.debug('Trouble with t3 synchronizer')
    Time.sleep(5)
# this sleep allows the threads to start so they will return a True for isAlive()
    while True:
        try:
            if t1().isAlive()==False:
                try:
                    t1().start()
                except:
                    log.debug('Trouble with t1 synchronizer')
            if t2.isAlive()==False:
                try:
                    t2().start()
                except:
                    log.debug('Trouble with t2 synchronizer')
            if t2.isAlive()==False()
               try:
                    t3().start()
                except:
                    log.debug('Trouble with t3 synchronizer')

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