| 96 | |
| 97 | |
| 98 | class SynchronizerImpl(object): |
| 99 | def __init__(self): |
| 100 | self._state = util.ThreadLocal() |
| 101 | |
| 102 | class SyncState(object): |
| 103 | __slots__ = 'reentrantcount', 'writing', 'reading' |
| 104 | |
| 105 | def __init__(self): |
| 106 | self.reentrantcount = 0 |
| 107 | self.writing = False |
| 108 | self.reading = False |
| 109 | |
| 110 | def state(self): |
| 111 | if not self._state.has(): |
| 112 | state = SynchronizerImpl.SyncState() |
| 113 | self._state.put(state) |
| 114 | return state |
| 115 | else: |
| 116 | return self._state.get() |
| 117 | state = property(state) |
| 118 | |
| 119 | def release_read_lock(self): |
| 120 | state = self.state |
| 121 | |
| 122 | if state.writing: |
| 123 | raise LockError("lock is in writing state") |
| 124 | if not state.reading: |
| 125 | raise LockError("lock is not in reading state") |
| 126 | |
| 127 | if state.reentrantcount == 1: |
| 128 | self.do_release_read_lock() |
| 129 | state.reading = False |
| 130 | |
| 131 | state.reentrantcount -= 1 |
| 132 | |
| 133 | def acquire_read_lock(self, wait = True): |
| 134 | state = self.state |
| 135 | |
| 136 | if state.writing: |
| 137 | raise LockError("lock is in writing state") |
| 138 | |
| 139 | if state.reentrantcount == 0: |
| 140 | x = self.do_acquire_read_lock(wait) |
| 141 | if (wait or x): |
| 142 | state.reentrantcount += 1 |
| 143 | state.reading = True |
| 144 | return x |
| 145 | elif state.reading: |
| 146 | state.reentrantcount += 1 |
| 147 | return True |
| 148 | |
| 149 | def release_write_lock(self): |
| 150 | state = self.state |
| 151 | |
| 152 | if state.reading: |
| 153 | raise LockError("lock is in reading state") |
| 154 | if not state.writing: |
| 155 | raise LockError("lock is not in writing state") |