Skip to content

Commit

Permalink
pythongh-126434: Use multiprocessing.Value for multiprocessing.Event …
Browse files Browse the repository at this point in the history
…to avoid deadlock when there is reentrant usage of `set` from `is_set`, e.g. when handling system signals
  • Loading branch information
ivarref committed Nov 11, 2024
1 parent 78842e4 commit e5302e6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
26 changes: 13 additions & 13 deletions Lib/multiprocessing/synchronize.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,34 +329,34 @@ class Event(object):

def __init__(self, *, ctx):
self._cond = ctx.Condition(ctx.Lock())
self._flag = ctx.Semaphore(0)
self._flag = ctx.Value('i', 0)

def is_set(self):
with self._cond:
if self._flag.acquire(False):
self._flag.release()
return True
return False
return self._flag.value == 1

def set(self):
assert not self._cond._lock._semlock._is_mine(), \
'multiprocessing.Event is not reentrant for clear(), set() and wait()'
with self._cond:
self._flag.acquire(False)
self._flag.release()
self._flag.value = 1
self._cond.notify_all()

def clear(self):
assert not self._cond._lock._semlock._is_mine(), \
'multiprocessing.Event is not reentrant for clear(), set() and wait()'
with self._cond:
self._flag.acquire(False)
self._flag.value = 0

def wait(self, timeout=None):
assert not self._cond._lock._semlock._is_mine(), \
'multiprocessing.Event is not reentrant for clear(), set() and wait()'
with self._cond:
if self._flag.acquire(False):
self._flag.release()
if self._flag.value == 1:
return True
else:
self._cond.wait(timeout)

if self._flag.acquire(False):
self._flag.release()
if self._flag.value == 1:
return True
return False

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Use :mod:`multiprocessing` ``Value`` for :mod:`multiprocessing` ``Event`` to avoid deadlock when reetrant usage of `set` from `is_set`, e.g. when handling system signals

0 comments on commit e5302e6

Please sign in to comment.