繁体   English   中英

如何确保只有一个线程实例在Python中运行?

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

我有一个带有三个线程的程序。 我这样称呼他们:

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

我想让这3个线程一直运行。 但是我还想确保一次同时运行t1,t2和t3中的每个实例。

编辑

我能想到的唯一解决方案是在每个线程中都有锁定文件。 有点像

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

但是以某种方式,它对我来说似乎不是一个干净的解决方案,因为该程序可能由于某种原因而退出了,线程可能根本无法启动。

您是一种正确的方法,可以确保每个线程仅使用锁文件运行一次。

还有什么方法可以检查它们是否正在运行,而不是不断尝试运行它们。 通过使用以下代码

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

暂无
暂无

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

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