python - 如何避免同一个函数的多个运行实例

时间:2016-09-25 15:29:07

标签: python function

在我的python脚本中,我有一个core dumped,我认为这是因为同一个函数同时被调用了两次。

该功能是在gtk窗口中读取Vte终端

def term(self, dPluzz, donnees=None):
    text = str(self.v.get_text(lambda *a: True).rstrip())
    [...]
    print "Here is the time " + str(time.time())

def terminal(self):    
    self.v = vte.Terminal()
    self.v.set_emulation('xterm')
    self.v.connect ("child-exited", lambda term: self.verif(self, dPluzz))
    self.v.connect("contents-changed", self.term)

结果:

Here is the time 1474816913.68
Here is the time 1474816913.68
Erreur de segmentation (core dumped)

如何避免双重执行该功能?

2 个答案:

答案 0 :(得分:1)

双重执行必须是contents-changed事件触发两次的结果。

您可以检查term函数是否已经执行过,如果已经执行,则退出。

term函数的开头添加这两行:

    if hasattr(self, 'term_has_executed'): return
    self.term_has_executed = True

答案 1 :(得分:0)

我创建了一个python装饰器(兼容多平台),该装饰器提供了避免并行执行的机制。 用法是:

@lock('file.lock')
def run():
    # Function action
    pass

过时的,我习惯于使用相对路径:

CURRENT_FILE_DIR = os.path.dirname(os.path.abspath(__file__))
@lock(os.path.join(CURRENT_FILE_DIR, os.path.basename(__file__)+".lock"))

装饰器:

import os

def lock(lock_file):
    """
    Usage:
        @lock('file.lock')
        def run():
            # Function action
    """
    def decorator(target):

        def wrapper(*args, **kwargs):

            if os.path.exists(lock_file):
                raise Exception('Unable to get exclusive lock.')
            else:
                with open(lock_file, "w") as f:
                    f.write("LOCK")

            # Execute the target
            result = target(*args, **kwargs)

            remove_attempts = 10
            os.remove(lock_file)
            while os.path.exists(lock_file) and remove_attempts >= 1:

                os.remove(lock_file)
                remove_attempts-=1

            return result
        return wrapper
    return decorator

用于多线程调用

有一个用于管理多线程调用的unix解决方案:https://gist.github.com/mvliet/5715690

别忘了感谢要旨的作者(不是我)。