lock.py
62 lines
| 1.5 KiB
| text/x-python
|
PythonLexer
/ mercurial / lock.py
mpm@selenic.com
|
r161 | # lock.py - simple locking scheme for mercurial | ||
# | ||||
# Copyright 2005 Matt Mackall <mpm@selenic.com> | ||||
# | ||||
# This software may be used and distributed according to the terms | ||||
# of the GNU General Public License, incorporated herein by reference. | ||||
Benoit Boissinot
|
r1753 | import errno, os, time | ||
mpm@selenic.com
|
r422 | import util | ||
mpm@selenic.com
|
r161 | |||
Benoit Boissinot
|
r1753 | class LockException(Exception): | ||
pass | ||||
class LockHeld(LockException): | ||||
pass | ||||
class LockUnavailable(LockException): | ||||
mpm@selenic.com
|
r161 | pass | ||
Eric Hopper
|
r1559 | class lock(object): | ||
Benoit Boissinot
|
r1787 | def __init__(self, file, timeout=-1, releasefn=None): | ||
mpm@selenic.com
|
r161 | self.f = file | ||
self.held = 0 | ||||
Benoit Boissinot
|
r1787 | self.timeout = timeout | ||
Benoit Boissinot
|
r1530 | self.releasefn = releasefn | ||
mpm@selenic.com
|
r161 | self.lock() | ||
def __del__(self): | ||||
self.release() | ||||
def lock(self): | ||||
Benoit Boissinot
|
r1787 | timeout = self.timeout | ||
mpm@selenic.com
|
r161 | while 1: | ||
try: | ||||
self.trylock() | ||||
return 1 | ||||
except LockHeld, inst: | ||||
Benoit Boissinot
|
r1787 | if timeout != 0: | ||
mpm@selenic.com
|
r161 | time.sleep(1) | ||
Benoit Boissinot
|
r1787 | if timeout > 0: | ||
timeout -= 1 | ||||
mpm@selenic.com
|
r161 | continue | ||
raise inst | ||||
mpm@selenic.com
|
r515 | |||
mpm@selenic.com
|
r161 | def trylock(self): | ||
pid = os.getpid() | ||||
try: | ||||
mpm@selenic.com
|
r422 | util.makelock(str(pid), self.f) | ||
mpm@selenic.com
|
r161 | self.held = 1 | ||
Benoit Boissinot
|
r1753 | except (OSError, IOError), why: | ||
if why.errno == errno.EEXIST: | ||||
raise LockHeld(util.readlock(self.f)) | ||||
else: | ||||
raise LockUnavailable(why) | ||||
mpm@selenic.com
|
r161 | |||
def release(self): | ||||
if self.held: | ||||
self.held = 0 | ||||
Benoit Boissinot
|
r1530 | if self.releasefn: | ||
self.releasefn() | ||||
mpm@selenic.com
|
r503 | try: | ||
os.unlink(self.f) | ||||
except: pass | ||||
mpm@selenic.com
|
r161 | |||