diff --git a/paddlehub/commands/hub.py b/paddlehub/commands/hub.py index 5618a1991938c3ac43c25bcf05135c2531d0c74f..257afc296ca4637893e219566d328959366640c8 100644 --- a/paddlehub/commands/hub.py +++ b/paddlehub/commands/hub.py @@ -19,6 +19,7 @@ from __future__ import print_function import six import sys +import os from paddlehub.common.logger import logger from paddlehub.common.utils import sys_stdin_encoding @@ -29,6 +30,8 @@ from paddlehub.commands import help from paddlehub.commands import version from paddlehub.commands import run from paddlehub.commands import download +from paddlehub.common.lock import lock +from paddlehub.common.dir import CONF_HOME class HubCommand(BaseCommand): @@ -66,7 +69,10 @@ def main(): argv.append(item.decode(sys_stdin_encoding()).decode("utf8")) else: argv.append(item) + fp_lock = open(os.path.join(CONF_HOME, 'config.json')) + lock.flock(fp_lock, lock.LOCK_EX) command.execute(argv[1:]) + lock.flock(fp_lock, lock.LOCK_UN) if __name__ == "__main__": diff --git a/paddlehub/common/lock.py b/paddlehub/common/lock.py index 5cc607cd327ea5a674d31dd44d0e214f393375d2..1afa08e7f9ce7e092ea4bcdac493ea2020e8dceb 100644 --- a/paddlehub/common/lock.py +++ b/paddlehub/common/lock.py @@ -13,14 +13,34 @@ class WinLock(object): class Lock(object): + _owner = None + def __init__(self): + self.LOCK_EX = fcntl.LOCK_EX + self.LOCK_UN = fcntl.LOCK_UN + self.LOCK_TE = "" if os.name == "posix": self.lock = fcntl else: self.lock = WinLock() + _lock = self.lock def get_lock(self): return self.lock - -lock = Lock().get_lock() + def flock(self, fp, cmd): + if cmd == fcntl.LOCK_UN: + Lock._owner = None + self.lock.flock(fp, cmd) + elif cmd == fcntl.LOCK_EX: + if Lock._owner is None: + Lock._owner = os.getpid() + self.lock.flock(fp, cmd) + else: + if Lock._owner == os.getpid(): + pass + else: + self.lock.flock(fp, cmd) + + +lock = Lock()