~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/counted_lock.py

  • Committer: Martin Pool
  • Date: 2009-03-24 05:21:02 UTC
  • mfrom: (4192 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4202.
  • Revision ID: mbp@sourcefrog.net-20090324052102-8kk087b32tep3d9h
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Counted lock class"""
18
18
 
19
19
 
20
 
from bzrlib.errors import (
21
 
    LockError,
22
 
    ReadOnlyError,
 
20
from bzrlib import (
 
21
    errors,
23
22
    )
24
23
 
25
24
 
26
 
# TODO: Pass through lock tokens on lock_write and read, and return them...
27
 
#
28
 
# TODO: Allow upgrading read locks to write?  Conceptually difficult.
29
 
 
30
 
 
31
25
class CountedLock(object):
32
26
    """Decorator around a lock that makes it reentrant.
33
27
 
43
37
        self._lock_mode = None
44
38
        self._lock_count = 0
45
39
 
 
40
    def __repr__(self):
 
41
        return "%s(%r)" % (self.__class__.__name__,
 
42
            self._real_lock)
 
43
 
46
44
    def break_lock(self):
47
45
        self._real_lock.break_lock()
48
46
        self._lock_mode = None
79
77
        if self._lock_count == 0:
80
78
            self._token = self._real_lock.lock_write(token=token)
81
79
            self._lock_mode = 'w'
 
80
            self._lock_count += 1
 
81
            return self._token
82
82
        elif self._lock_mode != 'w':
83
 
            raise ReadOnlyError(self)
84
 
        self._lock_count += 1
85
 
        return self._token
 
83
            raise errors.ReadOnlyError(self)
 
84
        else:
 
85
            self._real_lock.validate_token(token)
 
86
            self._lock_count += 1
 
87
            return token
86
88
 
87
89
    def unlock(self):
88
90
        if self._lock_count == 0:
89
 
            raise LockError("%s not locked" % (self,))
 
91
            raise errors.LockNotHeld(self)
90
92
        elif self._lock_count == 1:
 
93
            # these are decremented first; if we fail to unlock the most
 
94
            # reasonable assumption is that we still don't have the lock
 
95
            # anymore
 
96
            self._lock_mode = None
 
97
            self._lock_count -= 1
91
98
            self._real_lock.unlock()
92
 
            self._lock_mode = None
93
 
        self._lock_count -= 1
 
99
        else:
 
100
            self._lock_count -= 1