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

Skip to content

Commit 3eaac01

Browse files
committed
Ensure multiprocessing lock is valid for spawn Process before serializing it
1 parent 70dc009 commit 3eaac01

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

Lib/multiprocessing/synchronize.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ class SemLock(object):
5050
def __init__(self, kind, value, maxvalue, *, ctx):
5151
if ctx is None:
5252
ctx = context._default_context.get_context()
53-
name = ctx.get_start_method()
54-
unlink_now = sys.platform == 'win32' or name == 'fork'
53+
self.is_fork_ctx = ctx.get_start_method() == 'fork'
54+
unlink_now = sys.platform == 'win32' or self.is_fork_ctx
5555
for i in range(100):
5656
try:
5757
sl = self._semlock = _multiprocessing.SemLock(
@@ -103,6 +103,11 @@ def __getstate__(self):
103103
if sys.platform == 'win32':
104104
h = context.get_spawning_popen().duplicate_for_child(sl.handle)
105105
else:
106+
if self.is_fork_ctx:
107+
raise RuntimeError('A SemLock created in a fork context is being '
108+
'shared with a process in a spawn context. This is '
109+
'not supported. Please use the same context to create '
110+
'multiprocessing objects and Process.')
106111
h = sl.handle
107112
return (h, sl.kind, sl.maxvalue, sl.name)
108113

Lib/test/_test_multiprocessing.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6155,3 +6155,9 @@ class SemLock(_multiprocessing.SemLock):
61556155
name = f'test_semlock_subclass-{os.getpid()}'
61566156
s = SemLock(1, 0, 10, name, False)
61576157
_multiprocessing.sem_unlink(name)
6158+
6159+
def test_semlock_mixed_context(self):
6160+
queue = multiprocessing.get_context("fork").Queue()
6161+
p = multiprocessing.get_context("spawn").Process(target=close_queue, args=(queue,))
6162+
with self.assertRaisesRegex(RuntimeError, "A SemLock created in a fork"):
6163+
p.start()

0 commit comments

Comments
 (0)