Skip to content

Commit aee297a

Browse files
author
Benedikt Schmitt
committed
Merge branch 'issue#37'
2 parents 14f0303 + 509a366 commit aee297a

File tree

1 file changed

+27
-24
lines changed

1 file changed

+27
-24
lines changed

filelock.py

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,29 @@ def __str__(self):
105105

106106
# Classes
107107
# ------------------------------------------------
108+
109+
# This is a helper class which is returned by :meth:`BaseFileLock.acquire`
110+
# and wraps the lock to make sure __enter__ is not called twice when entering
111+
# the with statement.
112+
# If we would simply return *self*, the lock would be acquired again
113+
# in the *__enter__* method of the BaseFileLock, but not released again
114+
# automatically.
115+
#
116+
# :seealso: issue #37 (memory leak)
117+
class _Acquire_ReturnProxy(object):
118+
119+
def __init__(self, lock):
120+
self.lock = lock
121+
return None
122+
123+
def __enter__(self):
124+
return self.lock
125+
126+
def __exit__(self, exc_type, exc_value, traceback):
127+
self.lock.release()
128+
return None
129+
130+
108131
class BaseFileLock(object):
109132
"""
110133
Implements the base class of a file lock.
@@ -239,12 +262,11 @@ def acquire(self, timeout=None, poll_intervall=0.05):
239262
with self._thread_lock:
240263
self._lock_counter += 1
241264

265+
lock_id = id(self)
266+
lock_filename = self._lock_file
267+
start_time = time.time()
242268
try:
243-
start_time = time.time()
244269
while True:
245-
lock_id = id(self)
246-
lock_filename = self._lock_file
247-
248270
with self._thread_lock:
249271
if not self.is_locked:
250272
logger().debug('Attempting to acquire lock %s on %s', lock_id, lock_filename)
@@ -268,26 +290,7 @@ def acquire(self, timeout=None, poll_intervall=0.05):
268290
self._lock_counter = max(0, self._lock_counter - 1)
269291

270292
raise
271-
272-
# This class wraps the lock to make sure __enter__ is not called
273-
# twiced when entering the with statement.
274-
# If we would simply return *self*, the lock would be acquired again
275-
# in the *__enter__* method of the BaseFileLock, but not released again
276-
# automatically.
277-
class ReturnProxy(object):
278-
279-
def __init__(self, lock):
280-
self.lock = lock
281-
return None
282-
283-
def __enter__(self):
284-
return self.lock
285-
286-
def __exit__(self, exc_type, exc_value, traceback):
287-
self.lock.release()
288-
return None
289-
290-
return ReturnProxy(lock = self)
293+
return _Acquire_ReturnProxy(lock = self)
291294

292295
def release(self, force = False):
293296
"""

0 commit comments

Comments
 (0)