lockutils: catch BusyError when locking with timeout

If the IPC lock is used with a timeout value, an error can be raised. So
we need to catch it and convert it to a correct return value.

Change-Id: I7dbbf466905da3c6a1c7813f18fd3e9eb5ad2b47
This commit is contained in:
Julien Danjou 2014-07-31 14:05:23 +02:00
parent 1761de8f02
commit 9a37f27f61
2 changed files with 13 additions and 6 deletions

View File

@ -164,8 +164,11 @@ class _PosixLock(object):
self.semaphore = posix_ipc.Semaphore(self.name,
flags=posix_ipc.O_CREAT,
initial_value=1)
self.semaphore.acquire(timeout)
return self
try:
self.semaphore.acquire(timeout)
except posix_ipc.BusyError:
return False
return True
def __enter__(self):
self.acquire()

View File

@ -49,17 +49,21 @@ class LockTestCase(test_base.BaseTestCase):
self.assertEqual(foo.__name__, 'foo', "Wrapped function's name "
"got mangled")
def test_ipc_lock_timeout(self):
lock = lockutils.InterProcessLock('this is my lock')
self.assertTrue(lock.acquire())
self.assertFalse(lock.acquire(timeout=0))
def test_lock_acquire_release(self):
lock_name = 'a unique lock 123'
lock = lockutils.InterProcessLock(lock_name)
def try_lock():
try:
my_lock = lockutils.InterProcessLock(lock_name)
my_lock.acquire(0)
my_lock = lockutils.InterProcessLock(lock_name)
if my_lock.acquire(0):
my_lock.release()
os._exit(1)
except Exception:
else:
os._exit(0)
def attempt_acquire(count):