1
# Copyright (C) 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Counted lock class"""
25
class CountedLock(object):
26
"""Decorator around a lock that makes it reentrant.
28
This can be used with any object that provides a basic Lock interface,
29
including LockDirs and OS file locks.
32
def __init__(self, real_lock):
33
self._real_lock = real_lock
34
self._lock_mode = None
38
return "%s(%r)" % (self.__class__.__name__,
42
self._real_lock.break_lock()
43
self._lock_mode = None
47
return self._lock_mode is not None
50
"""Acquire the lock in read mode.
52
If the lock is already held in either read or write mode this
53
increments the count and succeeds. If the lock is not already held,
54
it is taken in read mode.
59
self._real_lock.lock_read()
63
def lock_write(self, token=None):
64
"""Acquire the lock in write mode.
66
If the lock was originally acquired in read mode this will fail.
68
:param token: If non-None, reacquire the lock using this token.
70
if self._lock_count == 0:
71
return_token = self._real_lock.lock_write(token)
75
elif self._lock_mode != 'w':
76
raise errors.ReadOnlyError(self)
78
self._real_lock.validate_token(token)
83
if self._lock_count == 0:
84
raise errors.LockNotHeld(self)
85
elif self._lock_count == 1:
86
# these are decremented first; if we fail to unlock the most
87
# reasonable assumption is that we still don't have the lock
89
self._lock_mode = None
91
self._real_lock.unlock()