Ranjith Ramachandra
Ranjith Ramachandra

Reputation: 10774

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.

Upvotes: 2

Views: 3207

Answers (1)

gabeio
gabeio

Reputation: 1320

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')

Upvotes: 2

Related Questions