Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 81a5855

Browse files
Issue #11714: Use 'with' statements to assure a Semaphore releases a
condition variable. Original patch by Thomas Rachel.
1 parent d4cb4b7 commit 81a5855

3 files changed

Lines changed: 22 additions & 20 deletions

File tree

Lib/threading.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -248,31 +248,29 @@ def acquire(self, blocking=True, timeout=None):
248248
raise ValueError("can't specify timeout for non-blocking acquire")
249249
rc = False
250250
endtime = None
251-
self._cond.acquire()
252-
while self._value == 0:
253-
if not blocking:
254-
break
255-
if timeout is not None:
256-
if endtime is None:
257-
endtime = _time() + timeout
258-
else:
259-
timeout = endtime - _time()
260-
if timeout <= 0:
261-
break
262-
self._cond.wait(timeout)
263-
else:
264-
self._value = self._value - 1
265-
rc = True
266-
self._cond.release()
251+
with self._cond:
252+
while self._value == 0:
253+
if not blocking:
254+
break
255+
if timeout is not None:
256+
if endtime is None:
257+
endtime = _time() + timeout
258+
else:
259+
timeout = endtime - _time()
260+
if timeout <= 0:
261+
break
262+
self._cond.wait(timeout)
263+
else:
264+
self._value = self._value - 1
265+
rc = True
267266
return rc
268267

269268
__enter__ = acquire
270269

271270
def release(self):
272-
self._cond.acquire()
273-
self._value = self._value + 1
274-
self._cond.notify()
275-
self._cond.release()
271+
with self._cond:
272+
self._value = self._value + 1
273+
self._cond.notify()
276274

277275
def __exit__(self, t, v, tb):
278276
self.release()

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,7 @@ Fernando Pérez
970970
Pierre Quentel
971971
Brian Quinlan
972972
Anders Qvist
973+
Thomas Rachel
973974
Jérôme Radix
974975
Burton Radons
975976
Jeff Ramnani

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ Core and Builtins
3636
Library
3737
-------
3838

39+
- Issue #11714: Use 'with' statements to assure a Semaphore releases a
40+
condition variable. Original patch by Thomas Rachel.
41+
3942
- Issue #17795: Reverted backwards-incompatible change in SysLogHandler with
4043
Unix domain sockets.
4144

0 commit comments

Comments
 (0)