Debian Codegraph @

py3.12/README_MODS

raw
1 cp -rf py3.11/examples .
2 cp -rf py3.11/doc .
3 cp -f py3.11/index.html .
4 cp -rf py3.11/_multiprocess _multiprocess
5 cp -rf py3.11/multiprocess multiprocess
6 cp -rf Python-3.11.0/Modules/_multiprocessing Modules/_multiprocess
7 # ----------------------------------------------------------------------
8 diff Python-3.12.0a1/Modules/_multiprocessing/semaphore.c Modules/_multiprocess/semaphore.c
9 10c10
10 < #include "multiprocessing.h"
11 ---
12 > #include "multiprocess.h"
13 35,36c35,36
14 < module _multiprocessing
15 < class _multiprocessing.SemLock "SemLockObject *" "&_PyMp_SemLockType"
16 ---
17 > module _multiprocess
18 > class _multiprocess.SemLock "SemLockObject *" "&_PyMp_SemLockType"
19 80c80
20 < _multiprocessing.SemLock.acquire
21 ---
22 > _multiprocess.SemLock.acquire
23 89c89
24 < _multiprocessing_SemLock_acquire_impl(SemLockObject *self, int blocking,
25 ---
26 > _multiprocess_SemLock_acquire_impl(SemLockObject *self, int blocking,
27 171c171
28 < _multiprocessing.SemLock.release
29 ---
30 > _multiprocess.SemLock.release
31 177c177
32 < _multiprocessing_SemLock_release_impl(SemLockObject *self)
33 ---
34 > _multiprocess_SemLock_release_impl(SemLockObject *self)
35 232c232
36 < #ifndef HAVE_SEM_TIMEDWAIT
37 ---
38 > // ifndef HAVE_SEM_TIMEDWAIT
39 293c293
40 < #endif /* !HAVE_SEM_TIMEDWAIT */
41 ---
42 > // #endif /* !HAVE_SEM_TIMEDWAIT */
43 296c296
44 < _multiprocessing.SemLock.acquire
45 ---
46 > _multiprocess.SemLock.acquire
47 305c305
48 < _multiprocessing_SemLock_acquire_impl(SemLockObject *self, int blocking,
49 ---
50 > _multiprocess_SemLock_acquire_impl(SemLockObject *self, int blocking,
51 381c381
52 < _multiprocessing.SemLock.release
53 ---
54 > _multiprocess.SemLock.release
55 387c387
56 < _multiprocessing_SemLock_release_impl(SemLockObject *self)
57 ---
58 > _multiprocess_SemLock_release_impl(SemLockObject *self)
59 471c471
60 < _multiprocessing.SemLock.__new__
61 ---
62 > _multiprocess.SemLock.__new__
63 482c482
64 < _multiprocessing_SemLock_impl(PyTypeObject *type, int kind, int value,
65 ---
66 > _multiprocess_SemLock_impl(PyTypeObject *type, int kind, int value,
67 530c530
68 < _multiprocessing.SemLock._rebuild
69 ---
70 > _multiprocess.SemLock._rebuild
71 541c541
72 < _multiprocessing_SemLock__rebuild_impl(PyTypeObject *type, SEM_HANDLE handle,
73 ---
74 > _multiprocess_SemLock__rebuild_impl(PyTypeObject *type, SEM_HANDLE handle,
75 581c581
76 < _multiprocessing.SemLock._count
77 ---
78 > _multiprocess.SemLock._count
79 587c587
80 < _multiprocessing_SemLock__count_impl(SemLockObject *self)
81 ---
82 > _multiprocess_SemLock__count_impl(SemLockObject *self)
83 594c594
84 < _multiprocessing.SemLock._is_mine
85 ---
86 > _multiprocess.SemLock._is_mine
87 600c600
88 < _multiprocessing_SemLock__is_mine_impl(SemLockObject *self)
89 ---
90 > _multiprocess_SemLock__is_mine_impl(SemLockObject *self)
91 608c608
92 < _multiprocessing.SemLock._get_value
93 ---
94 > _multiprocess.SemLock._get_value
95 614c614
96 < _multiprocessing_SemLock__get_value_impl(SemLockObject *self)
97 ---
98 > _multiprocess_SemLock__get_value_impl(SemLockObject *self)
99 633c633
100 < _multiprocessing.SemLock._is_zero
101 ---
102 > _multiprocess.SemLock._is_zero
103 639c639
104 < _multiprocessing_SemLock__is_zero_impl(SemLockObject *self)
105 ---
106 > _multiprocess_SemLock__is_zero_impl(SemLockObject *self)
107 661c661
108 < _multiprocessing.SemLock._after_fork
109 ---
110 > _multiprocess.SemLock._after_fork
111 667c667
112 < _multiprocessing_SemLock__after_fork_impl(SemLockObject *self)
113 ---
114 > _multiprocess_SemLock__after_fork_impl(SemLockObject *self)
115 675c675
116 < _multiprocessing.SemLock.__enter__
117 ---
118 > _multiprocess.SemLock.__enter__
119 681c681
120 < _multiprocessing_SemLock___enter___impl(SemLockObject *self)
121 ---
122 > _multiprocess_SemLock___enter___impl(SemLockObject *self)
123 684c684
124 < return _multiprocessing_SemLock_acquire_impl(self, 1, Py_None);
125 ---
126 > return _multiprocess_SemLock_acquire_impl(self, 1, Py_None);
127 688c688
128 < _multiprocessing.SemLock.__exit__
129 ---
130 > _multiprocess.SemLock.__exit__
131 699c699
132 < _multiprocessing_SemLock___exit___impl(SemLockObject *self,
133 ---
134 > _multiprocess_SemLock___exit___impl(SemLockObject *self,
135 704c704
136 < return _multiprocessing_SemLock_release_impl(self);
137 ---
138 > return _multiprocess_SemLock_release_impl(self);
139 759c759
140 < {Py_tp_new, _multiprocessing_SemLock},
141 ---
142 > {Py_tp_new, _multiprocess_SemLock},
143 767c767
144 < .name = "_multiprocessing.SemLock",
145 ---
146 > .name = "_multiprocess.SemLock",
147 diff Python-3.12.0a1/Modules/_multiprocessing/multiprocessing.c Modules/_multiprocess/multiprocess.c
148 2c2
149 < * Extension module used by multiprocessing package
150 ---
151 > * Extension module used by multiprocess package
152 4c4
153 < * multiprocessing.c
154 ---
155 > * multiprocess.c
156 10c10
157 < #include "multiprocessing.h"
158 ---
159 > #include "multiprocess.h"
160 29c29
161 < module _multiprocessing
162 ---
163 > module _multiprocess
164 76c76
165 < _multiprocessing.closesocket
166 ---
167 > _multiprocess.closesocket
168 84c84
169 < _multiprocessing_closesocket_impl(PyObject *module, HANDLE handle)
170 ---
171 > _multiprocess_closesocket_impl(PyObject *module, HANDLE handle)
172 99c99
173 < _multiprocessing.recv
174 ---
175 > _multiprocess.recv
176 108c108
177 < _multiprocessing_recv_impl(PyObject *module, HANDLE handle, int size)
178 ---
179 > _multiprocess_recv_impl(PyObject *module, HANDLE handle, int size)
180 131c131
181 < _multiprocessing.send
182 ---
183 > _multiprocess.send
184 140c140
185 < _multiprocessing_send_impl(PyObject *module, HANDLE handle, Py_buffer *buf)
186 ---
187 > _multiprocess_send_impl(PyObject *module, HANDLE handle, Py_buffer *buf)
188 159c159
189 < _multiprocessing.sem_unlink
190 ---
191 > _multiprocess.sem_unlink
192 167c167
193 < _multiprocessing_sem_unlink_impl(PyObject *module, const char *name)
194 ---
195 > _multiprocess_sem_unlink_impl(PyObject *module, const char *name)
196 195c195
197 < multiprocessing_exec(PyObject *module)
198 ---
199 > multiprocess_exec(PyObject *module)
200 277,278c277,278
201 < static PyModuleDef_Slot multiprocessing_slots[] = {
202 < {Py_mod_exec, multiprocessing_exec},
203 ---
204 > static PyModuleDef_Slot multiprocess_slots[] = {
205 > {Py_mod_exec, multiprocess_exec},
206 282c282
207 < static struct PyModuleDef multiprocessing_module = {
208 ---
209 > static struct PyModuleDef multiprocess_module = {
210 284c284
211 < .m_name = "_multiprocessing",
212 ---
213 > .m_name = "_multiprocess",
214 287c287
215 < .m_slots = multiprocessing_slots,
216 ---
217 > .m_slots = multiprocess_slots,
218 291c291
219 < PyInit__multiprocessing(void)
220 ---
221 > PyInit__multiprocess(void)
222 293c293
223 < return PyModuleDef_Init(&multiprocessing_module);
224 ---
225 > return PyModuleDef_Init(&multiprocess_module);
226 # ----------------------------------------------------------------------
227 diff Python-3.11.0/Lib/multiprocessing/managers.py Python-3.12.0a1/Lib/multiprocessing/managers.py
228 436d435
229 < obj, exposed, gettypeid = self.id_to_obj[ident]
230 diff Python-3.11.0/Lib/multiprocessing/resource_tracker.py Python-3.12.0a1/Lib/multiprocessing/resource_tracker.py
231 164c164
232 < if len(name) > 512:
233 ---
234 > if len(msg) > 512:
235 167c167
236 < raise ValueError('name too long')
237 ---
238 > raise ValueError('msg too long')
239 # ----------------------------------------------------------------------
240 diff Python-3.11.0/Lib/test/_test_multiprocessing.py Python-3.12.0a1/Lib/test/_test_multiprocessing.py
241 126a127,128
242 > WAIT_ACTIVE_CHILDREN_TIMEOUT = 5.0
243 >
244 4321,4325c4323,4325
245 < deadline = time.monotonic() + support.LONG_TIMEOUT
246 < t = 0.1
247 < while time.monotonic() < deadline:
248 < time.sleep(t)
249 < t = min(t*2, 5)
250 ---
251 > err_msg = ("A SharedMemory segment was leaked after "
252 > "a process was abruptly terminated")
253 > for _ in support.sleeping_retry(support.LONG_TIMEOUT, err_msg):
254 4330,4332d4329
255 < else:
256 < raise AssertionError("A SharedMemory segment was leaked after"
257 < " a process was abruptly terminated.")
258 5295c5292
259 < import time, os, tempfile
260 ---
261 > import time, os
262 5301d5297
263 < rand = tempfile._RandomNameSequence()
264 5342,5344c5338,5341
265 < deadline = time.monotonic() + support.LONG_TIMEOUT
266 < while time.monotonic() < deadline:
267 < time.sleep(.5)
268 ---
269 > err_msg = (f"A {rtype} resource was leaked after a process was "
270 > f"abruptly terminated")
271 > for _ in support.sleeping_retry(support.SHORT_TIMEOUT,
272 > err_msg):
273 5352,5355c5349
274 < else:
275 < raise AssertionError(
276 < f"A {rtype} resource was leaked after a process was "
277 < f"abruptly terminated.")
278 ---
279 >
280 5440a5435,5442
281 > def test_too_long_name_resource(self):
282 > # gh-96819: Resource names that will make the length of a write to a pipe
283 > # greater than PIPE_BUF are not allowed
284 > rtype = "shared_memory"
285 > too_long_name_resource = "a" * (512 - len(rtype))
286 > with self.assertRaises(ValueError):
287 > resource_tracker.register(too_long_name_resource, rtype)
288 >
289 5582a5585,5586
290 >
291 > timeout = WAIT_ACTIVE_CHILDREN_TIMEOUT
292 5584,5593c5588,5589
293 < t = 0.01
294 < while len(multiprocessing.active_children()) > 1:
295 < time.sleep(t)
296 < t *= 2
297 < dt = time.monotonic() - start_time
298 < if dt >= 5.0:
299 < test.support.environment_altered = True
300 < support.print_warning(f"multiprocessing.Manager still has "
301 < f"{multiprocessing.active_children()} "
302 < f"active children after {dt} seconds")
303 ---
304 > for _ in support.sleeping_retry(timeout, error=False):
305 > if len(multiprocessing.active_children()) <= 1:
306 5594a5591,5596
307 > else:
308 > dt = time.monotonic() - start_time
309 > support.environment_altered = True
310 > support.print_warning(f"multiprocessing.Manager still has "
311 > f"{multiprocessing.active_children()} "
312 > f"active children after {dt:.1f} seconds")
313 5699,5701c5701,5704
314 < assert obj[0] == 5
315 < assert obj.count(5) == 1
316 < assert obj.index(5) == 0
317 ---
318 > case = unittest.TestCase()
319 > case.assertEqual(obj[0], 5)
320 > case.assertEqual(obj.count(5), 1)
321 > case.assertEqual(obj.index(5), 0)
322 5706,5707c5709,5710
323 < assert len(obj) == 1
324 < assert obj.pop(0) == 5
325 ---
326 > case.assertEqual(len(obj), 1)
327 > case.assertEqual(obj.pop(0), 5)
328 5713c5716
329 < assert not o
330 ---
331 > self.assertIsNotNone(o)
332 5718,5725c5721,5729
333 < assert len(obj) == 1
334 < assert obj['foo'] == 5
335 < assert obj.get('foo') == 5
336 < assert list(obj.items()) == [('foo', 5)]
337 < assert list(obj.keys()) == ['foo']
338 < assert list(obj.values()) == [5]
339 < assert obj.copy() == {'foo': 5}
340 < assert obj.popitem() == ('foo', 5)
341 ---
342 > case = unittest.TestCase()
343 > case.assertEqual(len(obj), 1)
344 > case.assertEqual(obj['foo'], 5)
345 > case.assertEqual(obj.get('foo'), 5)
346 > case.assertListEqual(list(obj.items()), [('foo', 5)])
347 > case.assertListEqual(list(obj.keys()), ['foo'])
348 > case.assertListEqual(list(obj.values()), [5])
349 > case.assertDictEqual(obj.copy(), {'foo': 5})
350 > case.assertTupleEqual(obj.popitem(), ('foo', 5))
351 5731c5735
352 < assert not o
353 ---
354 > self.assertIsNotNone(o)
355 5736,5737c5740,5742
356 < assert obj.value == 1
357 < assert obj.get() == 1
358 ---
359 > case = unittest.TestCase()
360 > case.assertEqual(obj.value, 1)
361 > case.assertEqual(obj.get(), 1)
362 5748,5751c5753,5757
363 < assert obj[0] == 0
364 < assert obj[1] == 1
365 < assert len(obj) == 2
366 < assert list(obj) == [0, 1]
367 ---
368 > case = unittest.TestCase()
369 > case.assertEqual(obj[0], 0)
370 > case.assertEqual(obj[1], 1)
371 > case.assertEqual(len(obj), 2)
372 > case.assertListEqual(list(obj), [0, 1])
373 5759,5760c5765,5767
374 < assert obj.x == 0
375 < assert obj.y == 1
376 ---
377 > case = unittest.TestCase()
378 > case.assertEqual(obj.x, 0)
379 > case.assertEqual(obj.y, 1)
380 5890a5898
381 > timeout = WAIT_ACTIVE_CHILDREN_TIMEOUT
382 5892,5901c5900,5901
383 < t = 0.01
384 < while len(multiprocessing.active_children()) > 1:
385 < time.sleep(t)
386 < t *= 2
387 < dt = time.monotonic() - start_time
388 < if dt >= 5.0:
389 < test.support.environment_altered = True
390 < support.print_warning(f"multiprocessing.Manager still has "
391 < f"{multiprocessing.active_children()} "
392 < f"active children after {dt} seconds")
393 ---
394 > for _ in support.sleeping_retry(timeout, error=False):
395 > if len(multiprocessing.active_children()) <= 1:
396 5902a5903,5908
397 > else:
398 > dt = time.monotonic() - start_time
399 > support.environment_altered = True
400 > support.print_warning(f"multiprocessing.Manager still has "
401 > f"{multiprocessing.active_children()} "
402 > f"active children after {dt:.1f} seconds")
403 # ----------------------------------------------------------------------
404 diff Python-3.12.0a2/Modules/_multiprocessing/semaphore.c Python-3.12.0a3/Modules/_multiprocessing/semaphore.c
405 82c82
406 < block as blocking: bool(accept={int}) = True
407 ---
408 > block as blocking: bool = True
409 91c91
410 < /*[clinic end generated code: output=f9998f0b6b0b0872 input=86f05662cf753eb4]*/
411 ---
412 > /*[clinic end generated code: output=f9998f0b6b0b0872 input=e5b45f5cbb775166]*/
413 298c298
414 < block as blocking: bool(accept={int}) = True
415 ---
416 > block as blocking: bool = True
417 307c307
418 < /*[clinic end generated code: output=f9998f0b6b0b0872 input=86f05662cf753eb4]*/
419 ---
420 > /*[clinic end generated code: output=f9998f0b6b0b0872 input=e5b45f5cbb775166]*/
421 477c477
422 < unlink: bool(accept={int})
423 ---
424 > unlink: bool
425 484c484
426 < /*[clinic end generated code: output=30727e38f5f7577a input=b378c3ee27d3a0fa]*/
427 ---
428 > /*[clinic end generated code: output=30727e38f5f7577a input=fdaeb69814471c5b]*/
429 diff Python-3.12.0a2/Modules/_multiprocessing/clinic/semaphore.c.h Python-3.12.0a3/Modules/_multiprocessing/clinic/semaphore.c.h
430 68,69c68,69
431 < blocking = _PyLong_AsInt(args[0]);
432 < if (blocking == -1 && PyErr_Occurred()) {
433 ---
434 > blocking = PyObject_IsTrue(args[0]);
435 > if (blocking < 0) {
436 165,166c165,166
437 < blocking = _PyLong_AsInt(args[0]);
438 < if (blocking == -1 && PyErr_Occurred()) {
439 ---
440 > blocking = PyObject_IsTrue(args[0]);
441 > if (blocking < 0) {
442 278,279c278,279
443 < unlink = _PyLong_AsInt(fastargs[4]);
444 < if (unlink == -1 && PyErr_Occurred()) {
445 ---
446 > unlink = PyObject_IsTrue(fastargs[4]);
447 > if (unlink < 0) {
448 545c545
449 < /*[clinic end generated code: output=720d7d0066dc0954 input=a9049054013a1b77]*/
450 ---
451 > /*[clinic end generated code: output=dae57a702cc01512 input=a9049054013a1b77]*/
452 diff Python-3.12.0a2/Lib/multiprocessing/connection.py Python-3.12.0a3/Lib/multiprocessing/connection.py
453 730a731,798
454 > # multiprocessing.connection Authentication Handshake Protocol Description
455 > # (as documented for reference after reading the existing code)
456 > # =============================================================================
457 > #
458 > # On Windows: native pipes with "overlapped IO" are used to send the bytes,
459 > # instead of the length prefix SIZE scheme described below. (ie: the OS deals
460 > # with message sizes for us)
461 > #
462 > # Protocol error behaviors:
463 > #
464 > # On POSIX, any failure to receive the length prefix into SIZE, for SIZE greater
465 > # than the requested maxsize to receive, or receiving fewer than SIZE bytes
466 > # results in the connection being closed and auth to fail.
467 > #
468 > # On Windows, receiving too few bytes is never a low level _recv_bytes read
469 > # error, receiving too many will trigger an error only if receive maxsize
470 > # value was larger than 128 OR the if the data arrived in smaller pieces.
471 > #
472 > # Serving side Client side
473 > # ------------------------------ ---------------------------------------
474 > # 0. Open a connection on the pipe.
475 > # 1. Accept connection.
476 > # 2. New random 20 bytes -> MESSAGE
477 > # 3. send 4 byte length (net order)
478 > # prefix followed by:
479 > # b'#CHALLENGE#' + MESSAGE
480 > # 4. Receive 4 bytes, parse as network byte
481 > # order integer. If it is -1, receive an
482 > # additional 8 bytes, parse that as network
483 > # byte order. The result is the length of
484 > # the data that follows -> SIZE.
485 > # 5. Receive min(SIZE, 256) bytes -> M1
486 > # 6. Assert that M1 starts with:
487 > # b'#CHALLENGE#'
488 > # 7. Strip that prefix from M1 into -> M2
489 > # 8. Compute HMAC-MD5 of AUTHKEY, M2 -> C_DIGEST
490 > # 9. Send 4 byte length prefix (net order)
491 > # followed by C_DIGEST bytes.
492 > # 10. Compute HMAC-MD5 of AUTHKEY,
493 > # MESSAGE into -> M_DIGEST.
494 > # 11. Receive 4 or 4+8 byte length
495 > # prefix (#4 dance) -> SIZE.
496 > # 12. Receive min(SIZE, 256) -> C_D.
497 > # 13. Compare M_DIGEST == C_D:
498 > # 14a: Match? Send length prefix &
499 > # b'#WELCOME#'
500 > # <- RETURN
501 > # 14b: Mismatch? Send len prefix &
502 > # b'#FAILURE#'
503 > # <- CLOSE & AuthenticationError
504 > # 15. Receive 4 or 4+8 byte length prefix (net
505 > # order) again as in #4 into -> SIZE.
506 > # 16. Receive min(SIZE, 256) bytes -> M3.
507 > # 17. Compare M3 == b'#WELCOME#':
508 > # 17a. Match? <- RETURN
509 > # 17b. Mismatch? <- CLOSE & AuthenticationError
510 > #
511 > # If this RETURNed, the connection remains open: it has been authenticated.
512 > #
513 > # Length prefixes are used consistently even though every step so far has
514 > # always been a singular specific fixed length. This may help us evolve
515 > # the protocol in the future without breaking backwards compatibility.
516 > #
517 > # Similarly the initial challenge message from the serving side has always
518 > # been 20 bytes, but clients can accept a 100+ so using the length of the
519 > # opening challenge message as an indicator of protocol version may work.
520 >
521 >
522 diff Python-3.12.0a2/Lib/multiprocessing/pool.py Python-3.12.0a3/Lib/multiprocessing/pool.py
523 699c699
524 < "Cannot have cache with result_hander not alive")
525 ---
526 > "Cannot have cache with result_handler not alive")
527 diff Python-3.12.0a2/Lib/multiprocessing/shared_memory.py Python-3.12.0a3/Lib/multiprocessing/shared_memory.py
528 176c176,179
529 < size = _winapi.VirtualQuerySize(p_buf)
530 ---
531 > try:
532 > size = _winapi.VirtualQuerySize(p_buf)
533 > finally:
534 > _winapi.UnmapViewOfFile(p_buf)
535 diff Python-3.12.0a2/Lib/test/_test_multiprocessing.py Python-3.12.0a3/Lib/test/_test_multiprocessing.py
536 6045c6045
537 < s = SemLock(1, 0, 10, name, 0)
538 ---
539 > s = SemLock(1, 0, 10, name, False)
540 # ----------------------------------------------------------------------
541 diff Python-3.12.0a3/Lib/multiprocessing/queues.py Python-3.12.0a4/Lib/multiprocessing/queues.py
542 282a283,284
543 > __class_getitem__ = classmethod(types.GenericAlias)
544 >
545 # ----------------------------------------------------------------------
546 diff Python-3.12.0a4/Lib/multiprocessing/context.py Python-3.12.0a5/Lib/multiprocessing/context.py
547 260a261
548 > """Returns a list of the supported start methods, default first."""
549 # ----------------------------------------------------------------------
550 diff Python-3.12.0a4/Lib/test/_test_multiprocessing.py Python-3.12.0a5/Lib/test/_test_multiprocessing.py
551 4970c4970
552 < def run_in_child(cls):
553 ---
554 > def run_in_child(cls, start_method):
555 4972,4974c4972,4976
556 < r, w = multiprocessing.Pipe(duplex=False)
557 < p = multiprocessing.Process(target=cls.run_in_grandchild, args=(w,))
558 < p.start()
559 ---
560 > mp = multiprocessing.get_context(start_method)
561 > r, w = mp.Pipe(duplex=False)
562 > p = mp.Process(target=cls.run_in_grandchild, args=(w,))
563 > with warnings.catch_warnings(category=DeprecationWarning):
564 > p.start()
565 4985,4986c4987,4990
566 < prog = ('from test._test_multiprocessing import TestFlags; ' +
567 < 'TestFlags.run_in_child()')
568 ---
569 > prog = (
570 > 'from test._test_multiprocessing import TestFlags; '
571 > f'TestFlags.run_in_child({multiprocessing.get_start_method()!r})'
572 > )
573 # ----------------------------------------------------------------------
574 diff Python-3.12.0a5/Modules/_multiprocessing/multiprocessing.h Python-3.12.0a7/Modules/_multiprocessing/multiprocessing.h
575 15c15,17
576 < # define WIN32_LEAN_AND_MEAN
577 ---
578 > # ifndef WIN32_LEAN_AND_MEAN
579 > # define WIN32_LEAN_AND_MEAN
580 > # endif
581 # ----------------------------------------------------------------------
582 diff Python-3.12.0a7/Modules/_multiprocessing/multiprocessing.c Python-3.12.0b1/Modules/_multiprocessing/multiprocessing.c
583 278a279
584 > {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
585 diff Python-3.12.0a7/Modules/_multiprocessing/posixshmem.c Python-3.12.0b1/Modules/_multiprocessing/posixshmem.c
586 112a113,118
587 > static PyModuleDef_Slot module_slots[] = {
588 > {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
589 > {0, NULL}
590 > };
591 >
592 >
593 118a125
594 > .m_slots = module_slots,
595 diff Python-3.12.0a7/Lib/multiprocessing/connection.py Python-3.12.0b1/Lib/multiprocessing/connection.py
596 725c725
597 < MESSAGE_LENGTH = 20
598 ---
599 > MESSAGE_LENGTH = 40 # MUST be > 20
600 727,729c727,729
601 < CHALLENGE = b'#CHALLENGE#'
602 < WELCOME = b'#WELCOME#'
603 < FAILURE = b'#FAILURE#'
604 ---
605 > _CHALLENGE = b'#CHALLENGE#'
606 > _WELCOME = b'#WELCOME#'
607 > _FAILURE = b'#FAILURE#'
608 753c753,758
609 < # 2. New random 20 bytes -> MESSAGE
610 ---
611 > # 2. Random 20+ bytes -> MESSAGE
612 > # Modern servers always send
613 > # more than 20 bytes and include
614 > # a {digest} prefix on it with
615 > # their preferred HMAC digest.
616 > # Legacy ones send ==20 bytes.
617 766c771,778
618 < # 8. Compute HMAC-MD5 of AUTHKEY, M2 -> C_DIGEST
619 ---
620 > # 7.1. Parse M2: if it is exactly 20 bytes in
621 > # length this indicates a legacy server
622 > # supporting only HMAC-MD5. Otherwise the
623 > # 7.2. preferred digest is looked up from an
624 > # expected "{digest}" prefix on M2. No prefix
625 > # or unsupported digest? <- AuthenticationError
626 > # 7.3. Put divined algorithm name in -> D_NAME
627 > # 8. Compute HMAC-D_NAME of AUTHKEY, M2 -> C_DIGEST
628 769,771c781
629 < # 10. Compute HMAC-MD5 of AUTHKEY,
630 < # MESSAGE into -> M_DIGEST.
631 < # 11. Receive 4 or 4+8 byte length
632 ---
633 > # 10. Receive 4 or 4+8 byte length
634 773c783,796
635 < # 12. Receive min(SIZE, 256) -> C_D.
636 ---
637 > # 11. Receive min(SIZE, 256) -> C_D.
638 > # 11.1. Parse C_D: legacy servers
639 > # accept it as is, "md5" -> D_NAME
640 > # 11.2. modern servers check the length
641 > # of C_D, IF it is 16 bytes?
642 > # 11.2.1. "md5" -> D_NAME
643 > # and skip to step 12.
644 > # 11.3. longer? expect and parse a "{digest}"
645 > # prefix into -> D_NAME.
646 > # Strip the prefix and store remaining
647 > # bytes in -> C_D.
648 > # 11.4. Don't like D_NAME? <- AuthenticationError
649 > # 12. Compute HMAC-D_NAME of AUTHKEY,
650 > # MESSAGE into -> M_DIGEST.
651 790,796c813,863
652 < # Length prefixes are used consistently even though every step so far has
653 < # always been a singular specific fixed length. This may help us evolve
654 < # the protocol in the future without breaking backwards compatibility.
655 < #
656 < # Similarly the initial challenge message from the serving side has always
657 < # been 20 bytes, but clients can accept a 100+ so using the length of the
658 < # opening challenge message as an indicator of protocol version may work.
659 ---
660 > # Length prefixes are used consistently. Even on the legacy protocol, this
661 > # was good fortune and allowed us to evolve the protocol by using the length
662 > # of the opening challenge or length of the returned digest as a signal as
663 > # to which protocol the other end supports.
664 >
665 > _ALLOWED_DIGESTS = frozenset(
666 > {b'md5', b'sha256', b'sha384', b'sha3_256', b'sha3_384'})
667 > _MAX_DIGEST_LEN = max(len(_) for _ in _ALLOWED_DIGESTS)
668 >
669 > # Old hmac-md5 only server versions from Python <=3.11 sent a message of this
670 > # length. It happens to not match the length of any supported digest so we can
671 > # use a message of this length to indicate that we should work in backwards
672 > # compatible md5-only mode without a {digest_name} prefix on our response.
673 > _MD5ONLY_MESSAGE_LENGTH = 20
674 > _MD5_DIGEST_LEN = 16
675 > _LEGACY_LENGTHS = (_MD5ONLY_MESSAGE_LENGTH, _MD5_DIGEST_LEN)
676 >
677 >
678 > def _get_digest_name_and_payload(message: bytes) -> (str, bytes):
679 > """Returns a digest name and the payload for a response hash.
680 >
681 > If a legacy protocol is detected based on the message length
682 > or contents the digest name returned will be empty to indicate
683 > legacy mode where MD5 and no digest prefix should be sent.
684 > """
685 > # modern message format: b"{digest}payload" longer than 20 bytes
686 > # legacy message format: 16 or 20 byte b"payload"
687 > if len(message) in _LEGACY_LENGTHS:
688 > # Either this was a legacy server challenge, or we're processing
689 > # a reply from a legacy client that sent an unprefixed 16-byte
690 > # HMAC-MD5 response. All messages using the modern protocol will
691 > # be longer than either of these lengths.
692 > return '', message
693 > if (message.startswith(b'{') and
694 > (curly := message.find(b'}', 1, _MAX_DIGEST_LEN+2)) > 0):
695 > digest = message[1:curly]
696 > if digest in _ALLOWED_DIGESTS:
697 > payload = message[curly+1:]
698 > return digest.decode('ascii'), payload
699 > raise AuthenticationError(
700 > 'unsupported message length, missing digest prefix, '
701 > f'or unsupported digest: {message=}')
702 >
703 >
704 > def _create_response(authkey, message):
705 > """Create a MAC based on authkey and message
706 >
707 > The MAC algorithm defaults to HMAC-MD5, unless MD5 is not available or
708 > the message has a '{digest_name}' prefix. For legacy HMAC-MD5, the response
709 > is the raw MAC, otherwise the response is prefixed with '{digest_name}',
710 > e.g. b'{sha256}abcdefg...'
711 798,799c865,894
712 <
713 < def deliver_challenge(connection, authkey):
714 ---
715 > Note: The MAC protects the entire message including the digest_name prefix.
716 > """
717 > import hmac
718 > digest_name = _get_digest_name_and_payload(message)[0]
719 > # The MAC protects the entire message: digest header and payload.
720 > if not digest_name:
721 > # Legacy server without a {digest} prefix on message.
722 > # Generate a legacy non-prefixed HMAC-MD5 reply.
723 > try:
724 > return hmac.new(authkey, message, 'md5').digest()
725 > except ValueError:
726 > # HMAC-MD5 is not available (FIPS mode?), fall back to
727 > # HMAC-SHA2-256 modern protocol. The legacy server probably
728 > # doesn't support it and will reject us anyways. :shrug:
729 > digest_name = 'sha256'
730 > # Modern protocol, indicate the digest used in the reply.
731 > response = hmac.new(authkey, message, digest_name).digest()
732 > return b'{%s}%s' % (digest_name.encode('ascii'), response)
733 >
734 >
735 > def _verify_challenge(authkey, message, response):
736 > """Verify MAC challenge
737 >
738 > If our message did not include a digest_name prefix, the client is allowed
739 > to select a stronger digest_name from _ALLOWED_DIGESTS.
740 >
741 > In case our message is prefixed, a client cannot downgrade to a weaker
742 > algorithm, because the MAC is calculated over the entire message
743 > including the '{digest_name}' prefix.
744 > """
745 800a896,910
746 > response_digest, response_mac = _get_digest_name_and_payload(response)
747 > response_digest = response_digest or 'md5'
748 > try:
749 > expected = hmac.new(authkey, message, response_digest).digest()
750 > except ValueError:
751 > raise AuthenticationError(f'{response_digest=} unsupported')
752 > if len(expected) != len(response_mac):
753 > raise AuthenticationError(
754 > f'expected {response_digest!r} of length {len(expected)} '
755 > f'got {len(response_mac)}')
756 > if not hmac.compare_digest(expected, response_mac):
757 > raise AuthenticationError('digest received was wrong')
758 >
759 >
760 > def deliver_challenge(connection, authkey: bytes, digest_name='sha256'):
761 803a914
762 > assert MESSAGE_LENGTH > _MD5ONLY_MESSAGE_LENGTH, "protocol constraint"
763 805,806c916,920
764 < connection.send_bytes(CHALLENGE + message)
765 < digest = hmac.new(authkey, message, 'md5').digest()
766 ---
767 > message = b'{%s}%s' % (digest_name.encode('ascii'), message)
768 > # Even when sending a challenge to a legacy client that does not support
769 > # digest prefixes, they'll take the entire thing as a challenge and
770 > # respond to it with a raw HMAC-MD5.
771 > connection.send_bytes(_CHALLENGE + message)
772 808,809c922,926
773 < if response == digest:
774 < connection.send_bytes(WELCOME)
775 ---
776 > try:
777 > _verify_challenge(authkey, message, response)
778 > except AuthenticationError:
779 > connection.send_bytes(_FAILURE)
780 > raise
781 811,812c928
782 < connection.send_bytes(FAILURE)
783 < raise AuthenticationError('digest received was wrong')
784 ---
785 > connection.send_bytes(_WELCOME)
786 814,815c930,931
787 < def answer_challenge(connection, authkey):
788 < import hmac
789 ---
790 >
791 > def answer_challenge(connection, authkey: bytes):
792 820,822c936,942
793 < assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
794 < message = message[len(CHALLENGE):]
795 < digest = hmac.new(authkey, message, 'md5').digest()
796 ---
797 > if not message.startswith(_CHALLENGE):
798 > raise AuthenticationError(
799 > f'Protocol error, expected challenge: {message=}')
800 > message = message[len(_CHALLENGE):]
801 > if len(message) < _MD5ONLY_MESSAGE_LENGTH:
802 > raise AuthenticationError('challenge too short: {len(message)} bytes')
803 > digest = _create_response(authkey, message)
804 825c945
805 < if response != WELCOME:
806 ---
807 > if response != _WELCOME:
808 diff Python-3.12.0a7/Lib/multiprocessing/process.py Python-3.12.0b1/Lib/multiprocessing/process.py
809 64c64
810 < if p._popen.poll() is not None:
811 ---
812 > if (child_popen := p._popen) and child_popen.poll() is not None:
813 diff Python-3.12.0a7/Lib/test/_test_multiprocessing.py Python-3.12.0b1/Lib/test/_test_multiprocessing.py
814 50a51
815 > from multiprocessing.connection import wait, AuthenticationError
816 134,135d134
817 < from multiprocessing.connection import wait
818 <
819 3045c3044
820 < @hashlib_helper.requires_hashdigest('md5')
821 ---
822 > @hashlib_helper.requires_hashdigest('sha256')
823 3534c3533
824 < @hashlib_helper.requires_hashdigest('md5')
825 ---
826 > @hashlib_helper.requires_hashdigest('sha256')
827 3837c3836
828 < @hashlib_helper.requires_hashdigest('md5')
829 ---
830 > @hashlib_helper.requires_hashdigest('sha256')
831 4639c4638
832 < @hashlib_helper.requires_hashdigest('md5')
833 ---
834 > @hashlib_helper.requires_hashdigest('sha256')
835 4659c4658
836 < return multiprocessing.connection.CHALLENGE
837 ---
838 > return multiprocessing.connection._CHALLENGE
839 4668a4668,4705
840 >
841 > @hashlib_helper.requires_hashdigest('md5')
842 > @hashlib_helper.requires_hashdigest('sha256')
843 > class ChallengeResponseTest(unittest.TestCase):
844 > authkey = b'supadupasecretkey'
845 >
846 > def create_response(self, message):
847 > return multiprocessing.connection._create_response(
848 > self.authkey, message
849 > )
850 >
851 > def verify_challenge(self, message, response):
852 > return multiprocessing.connection._verify_challenge(
853 > self.authkey, message, response
854 > )
855 >
856 > def test_challengeresponse(self):
857 > for algo in [None, "md5", "sha256"]:
858 > with self.subTest(f"{algo=}"):
859 > msg = b'is-twenty-bytes-long' # The length of a legacy message.
860 > if algo:
861 > prefix = b'{%s}' % algo.encode("ascii")
862 > else:
863 > prefix = b''
864 > msg = prefix + msg
865 > response = self.create_response(msg)
866 > if not response.startswith(prefix):
867 > self.fail(response)
868 > self.verify_challenge(msg, response)
869 >
870 > # TODO(gpshead): We need integration tests for handshakes between modern
871 > # deliver_challenge() and verify_response() code and connections running a
872 > # test-local copy of the legacy Python <=3.11 implementations.
873 >
874 > # TODO(gpshead): properly annotate tests for requires_hashdigest rather than
875 > # only running these on a platform supporting everything. otherwise logic
876 > # issues preventing it from working on FIPS mode setups will be hidden.
877 >
878 4676c4713
879 < @hashlib_helper.requires_hashdigest('md5')
880 ---
881 > @hashlib_helper.requires_hashdigest('sha256')
882 5540c5577
883 < @hashlib_helper.requires_hashdigest('md5')
884 ---
885 > @hashlib_helper.requires_hashdigest('sha256')
886 5972c6009
887 < Temp = hashlib_helper.requires_hashdigest('md5')(Temp)
888 ---
889 > Temp = hashlib_helper.requires_hashdigest('sha256')(Temp)
890 # ----------------------------------------------------------------------
891 diff Python-3.12.0b1/Lib/multiprocessing/spawn.py Python-3.12.0b4/Lib/multiprocessing/spawn.py
892 34c34
893 < WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
894 ---
895 > WINSERVICE = sys.executable and sys.executable.lower().endswith("pythonservice.exe")
896 38c38,40
897 < if sys.platform == 'win32':
898 ---
899 > if exe is None:
900 > _python_exe = exe
901 > elif sys.platform == 'win32':
902 diff Python-3.12.0b1/Lib/test/_test_multiprocessing.py Python-3.12.0b4/Lib/test/_test_multiprocessing.py
903 15a16
904 > import functools
905 33a35
906 > from test.support import script_helper
907 173a176,228
908 > def only_run_in_spawn_testsuite(reason):
909 > """Returns a decorator: raises SkipTest when SM != spawn at test time.
910 >
911 > This can be useful to save overall Python test suite execution time.
912 > "spawn" is the universal mode available on all platforms so this limits the
913 > decorated test to only execute within test_multiprocessing_spawn.
914 >
915 > This would not be necessary if we refactored our test suite to split things
916 > into other test files when they are not start method specific to be rerun
917 > under all start methods.
918 > """
919 >
920 > def decorator(test_item):
921 >
922 > @functools.wraps(test_item)
923 > def spawn_check_wrapper(*args, **kwargs):
924 > if (start_method := multiprocessing.get_start_method()) != "spawn":
925 > raise unittest.SkipTest(f"{start_method=}, not 'spawn'; {reason}")
926 > return test_item(*args, **kwargs)
927 >
928 > return spawn_check_wrapper
929 >
930 > return decorator
931 >
932 >
933 > class TestInternalDecorators(unittest.TestCase):
934 > """Logic within a test suite that could errantly skip tests? Test it!"""
935 >
936 > @unittest.skipIf(sys.platform == "win32", "test requires that fork exists.")
937 > def test_only_run_in_spawn_testsuite(self):
938 > if multiprocessing.get_start_method() != "spawn":
939 > raise unittest.SkipTest("only run in test_multiprocessing_spawn.")
940 >
941 > try:
942 > @only_run_in_spawn_testsuite("testing this decorator")
943 > def return_four_if_spawn():
944 > return 4
945 > except Exception as err:
946 > self.fail(f"expected decorated `def` not to raise; caught {err}")
947 >
948 > orig_start_method = multiprocessing.get_start_method(allow_none=True)
949 > try:
950 > multiprocessing.set_start_method("spawn", force=True)
951 > self.assertEqual(return_four_if_spawn(), 4)
952 > multiprocessing.set_start_method("fork", force=True)
953 > with self.assertRaises(unittest.SkipTest) as ctx:
954 > return_four_if_spawn()
955 > self.assertIn("testing this decorator", str(ctx.exception))
956 > self.assertIn("start_method=", str(ctx.exception))
957 > finally:
958 > multiprocessing.set_start_method(orig_start_method, force=True)
959 >
960 >
961 5817a5873
962 > @only_run_in_spawn_testsuite("spawn specific test.")
963 5828d5883
964 <
965 5830d5884
966 <
967 5832d5885
968 <
969 5834d5886
970 <
971 5840c5892
972 < rc, out, err = test.support.script_helper.assert_python_ok(testfn)
973 ---
974 > rc, out, err = script_helper.assert_python_ok(testfn)
975 5843c5895
976 < self.assertEqual(err, b'')
977 ---
978 > self.assertFalse(err, msg=err.decode('utf-8'))
979 5851a5904,5921
980 > @only_run_in_spawn_testsuite("avoids redundant testing.")
981 > def test_spawn_sys_executable_none_allows_import(self):
982 > # Regression test for a bug introduced in
983 > # https://github.com/python/cpython/issues/90876 that caused an
984 > # ImportError in multiprocessing when sys.executable was None.
985 > # This can be true in embedded environments.
986 > rc, out, err = script_helper.assert_python_ok(
987 > "-c",
988 > """if 1:
989 > import sys
990 > sys.executable = None
991 > assert "multiprocessing" not in sys.modules, "already imported!"
992 > import multiprocessing
993 > import multiprocessing.spawn # This should not fail\n""",
994 > )
995 > self.assertEqual(rc, 0)
996 > self.assertFalse(err, msg=err.decode('utf-8'))
997 >
998 # ----------------------------------------------------------------------
999 diff Python-3.12.0b4/Modules/_multiprocessing/semaphore.c Python-3.12.0rc2/Modules/_multiprocessing/semaphore.c
1000 519,521d518
1001 < if (handle != SEM_FAILED)
1002 < SEM_CLOSE(handle);
1003 < PyMem_Free(name_copy);
1004 524a522,524
1005 > if (handle != SEM_FAILED)
1006 > SEM_CLOSE(handle);
1007 > PyMem_Free(name_copy);
1008 558a559
1009 > PyErr_SetFromErrno(PyExc_OSError);
1010 560c561
1011 < return PyErr_SetFromErrno(PyExc_OSError);
1012 ---
1013 > return NULL;
1014 diff Python-3.12.0b4/Lib/multiprocessing/forkserver.py Python-3.12.0rc2/Lib/multiprocessing/forkserver.py
1015 64c64
1016 < if not all(type(mod) is str for mod in self._preload_modules):
1017 ---
1018 > if not all(type(mod) is str for mod in modules_names):
1019 diff Python-3.12.0b4/Lib/multiprocessing/spawn.py Python-3.12.0rc2/Lib/multiprocessing/spawn.py
1020 153c153,157
1021 < is not going to be frozen to produce an executable.''')
1022 ---
1023 > is not going to be frozen to produce an executable.
1024 >
1025 > To fix this issue, refer to the "Safe importing of main module"
1026 > section in https://docs.python.org/3/library/multiprocessing.html
1027 > ''')
1028 diff Python-3.12.0b4/Lib/multiprocessing/synchronize.py Python-3.12.0rc2/Lib/multiprocessing/synchronize.py
1029 53,54c53,54
1030 < name = ctx.get_start_method()
1031 < unlink_now = sys.platform == 'win32' or name == 'fork'
1032 ---
1033 > self._is_fork_ctx = ctx.get_start_method() == 'fork'
1034 > unlink_now = sys.platform == 'win32' or self._is_fork_ctx
1035 105a106,110
1036 > if self._is_fork_ctx:
1037 > raise RuntimeError('A SemLock created in a fork context is being '
1038 > 'shared with a process in a spawn context. This is '
1039 > 'not supported. Please use the same context to create '
1040 > 'multiprocessing objects and Process.')
1041 112a118,119
1042 > # Ensure that deserialized SemLock can be serialized again (gh-108520).
1043 > self._is_fork_ctx = False
1044 diff Python-3.12.0b4/Lib/test/_test_multiprocessing.py Python-3.12.0rc2/Lib/test/_test_multiprocessing.py
1045 331a332
1046 > @support.requires_resource('cpu')
1047 4468a4470
1048 > @support.requires_resource('cpu')
1049 5333a5336,5343
1050 > def test_context_check_module_types(self):
1051 > try:
1052 > ctx = multiprocessing.get_context('forkserver')
1053 > except ValueError:
1054 > raise unittest.SkipTest('forkserver should be available')
1055 > with self.assertRaisesRegex(TypeError, 'module_names must be a list of strings'):
1056 > ctx.set_forkserver_preload([1, 2, 3])
1057 >
1058 5377a5388,5435
1059 > @unittest.skipIf(sys.platform == "win32",
1060 > "Only Spawn on windows so no risk of mixing")
1061 > @only_run_in_spawn_testsuite("avoids redundant testing.")
1062 > def test_mixed_startmethod(self):
1063 > # Fork-based locks cannot be used with spawned process
1064 > for process_method in ["spawn", "forkserver"]:
1065 > queue = multiprocessing.get_context("fork").Queue()
1066 > process_ctx = multiprocessing.get_context(process_method)
1067 > p = process_ctx.Process(target=close_queue, args=(queue,))
1068 > err_msg = "A SemLock created in a fork"
1069 > with self.assertRaisesRegex(RuntimeError, err_msg):
1070 > p.start()
1071 >
1072 > # non-fork-based locks can be used with all other start methods
1073 > for queue_method in ["spawn", "forkserver"]:
1074 > for process_method in multiprocessing.get_all_start_methods():
1075 > queue = multiprocessing.get_context(queue_method).Queue()
1076 > process_ctx = multiprocessing.get_context(process_method)
1077 > p = process_ctx.Process(target=close_queue, args=(queue,))
1078 > p.start()
1079 > p.join()
1080 >
1081 > @classmethod
1082 > def _put_one_in_queue(cls, queue):
1083 > queue.put(1)
1084 >
1085 > @classmethod
1086 > def _put_two_and_nest_once(cls, queue):
1087 > queue.put(2)
1088 > process = multiprocessing.Process(target=cls._put_one_in_queue, args=(queue,))
1089 > process.start()
1090 > process.join()
1091 >
1092 > def test_nested_startmethod(self):
1093 > # gh-108520: Regression test to ensure that child process can send its
1094 > # arguments to another process
1095 > queue = multiprocessing.Queue()
1096 >
1097 > process = multiprocessing.Process(target=self._put_two_and_nest_once, args=(queue,))
1098 > process.start()
1099 > process.join()
1100 >
1101 > results = []
1102 > while not queue.empty():
1103 > results.append(queue.get())
1104 >
1105 > self.assertEqual(results, [2, 1])
1106 >
1107 6061c6119,6120
1108 < def install_tests_in_module_dict(remote_globs, start_method):
1109 ---
1110 > def install_tests_in_module_dict(remote_globs, start_method,
1111 > only_type=None, exclude_types=False):
1112 6073a6133,6136
1113 > if only_type and type_ != only_type:
1114 > continue
1115 > if exclude_types:
1116 > continue
1117 6083a6147,6149
1118 > if only_type:
1119 > continue
1120 >
1121 # ----------------------------------------------------------------------
1122 diff Python-3.12.0rc2/Lib/test/_test_multiprocessing.py Python-3.12.0rc3/Lib/test/_test_multiprocessing.py
1123 677a678
1124 > @support.requires_resource('walltime')
1125 4955a4957
1126 > @support.requires_resource('walltime')
1127 4983a4986
1128 > @support.requires_resource('walltime')
1129 # ----------------------------------------------------------------------
1130 diff Python-3.12.0rc3/Lib/multiprocessing/connection.py Python-3.12.1/Lib/multiprocessing/connection.py
1131 11a12
1132 > import errno
1133 273a275
1134 > _send_ov = None
1135 275a278,281
1136 > ov = self._send_ov
1137 > if ov is not None:
1138 > # Interrupt WaitForMultipleObjects() in _send_bytes()
1139 > ov.cancel()
1140 278a285,288
1141 > if self._send_ov is not None:
1142 > # A connection should only be used by a single thread
1143 > raise ValueError("concurrent send_bytes() calls "
1144 > "are not supported")
1145 279a290
1146 > self._send_ov = ov
1147 288a300
1148 > self._send_ov = None
1149 289a302,306
1150 > if err == _winapi.ERROR_OPERATION_ABORTED:
1151 > # close() was called by another thread while
1152 > # WaitForMultipleObjects() was waiting for the overlapped
1153 > # operation.
1154 > raise OSError(errno.EPIPE, "handle is closed")
1155 diff Python-3.12.0rc3/Lib/multiprocessing/popen_spawn_win32.py Python-3.12.1/Lib/multiprocessing/popen_spawn_win32.py
1156 16a17
1157 > # Exit code used by Popen.terminate()
1158 125,126c126,130
1159 < except OSError:
1160 < if self.wait(timeout=1.0) is None:
1161 ---
1162 > except PermissionError:
1163 > # ERROR_ACCESS_DENIED (winerror 5) is received when the
1164 > # process already died.
1165 > code = _winapi.GetExitCodeProcess(int(self._handle))
1166 > if code == _winapi.STILL_ACTIVE:
1167 127a132,134
1168 > self.returncode = code
1169 > else:
1170 > self.returncode = -signal.SIGTERM
1171 diff Python-3.12.0rc3/Lib/multiprocessing/queues.py Python-3.12.1/Lib/multiprocessing/queues.py
1172 160a161,169
1173 > def _terminate_broken(self):
1174 > # Close a Queue on error.
1175 >
1176 > # gh-94777: Prevent queue writing to a pipe which is no longer read.
1177 > self._reader.close()
1178 >
1179 > self.close()
1180 > self.join_thread()
1181 >
1182 172c181,182
1183 < name='QueueFeederThread'
1184 ---
1185 > name='QueueFeederThread',
1186 > daemon=True,
1187 174d183
1188 < self._thread.daemon = True
1189 176,178c185,193
1190 < debug('doing self._thread.start()')
1191 < self._thread.start()
1192 < debug('... done self._thread.start()')
1193 ---
1194 > try:
1195 > debug('doing self._thread.start()')
1196 > self._thread.start()
1197 > debug('... done self._thread.start()')
1198 > except:
1199 > # gh-109047: During Python finalization, creating a thread
1200 > # can fail with RuntimeError.
1201 > self._thread = None
1202 > raise
1203 diff Python-3.12.0rc3/Lib/multiprocessing/resource_tracker.py Python-3.12.1/Lib/multiprocessing/resource_tracker.py
1204 53a54,57
1205 > class ReentrantCallError(RuntimeError):
1206 > pass
1207 >
1208 >
1209 57c61
1210 < self._lock = threading.Lock()
1211 ---
1212 > self._lock = threading.RLock()
1213 60a65,72
1214 > def _reentrant_call_error(self):
1215 > # gh-109629: this happens if an explicit call to the ResourceTracker
1216 > # gets interrupted by a garbage collection, invoking a finalizer (*)
1217 > # that itself calls back into ResourceTracker.
1218 > # (*) for example the SemLock finalizer
1219 > raise ReentrantCallError(
1220 > "Reentrant call into the multiprocessing resource tracker")
1221 >
1222 62a75,78
1223 > # This should not happen (_stop() isn't called by a finalizer)
1224 > # but we check for it anyway.
1225 > if self._lock._recursion_count() > 1:
1226 > return self._reentrant_call_error()
1227 83a100,102
1228 > if self._lock._recursion_count() > 1:
1229 > # The code below is certainly not reentrant-safe, so bail out
1230 > return self._reentrant_call_error()
1231 162c181,191
1232 < self.ensure_running()
1233 ---
1234 > try:
1235 > self.ensure_running()
1236 > except ReentrantCallError:
1237 > # The code below might or might not work, depending on whether
1238 > # the resource tracker was already running and still alive.
1239 > # Better warn the user.
1240 > # (XXX is warnings.warn itself reentrant-safe? :-)
1241 > warnings.warn(
1242 > f"ResourceTracker called reentrantly for resource cleanup, "
1243 > f"which is unsupported. "
1244 > f"The {rtype} object {name!r} might leak.")
1245 178a208
1246 >
1247 diff Python-3.12.0rc3/Lib/test/_test_multiprocessing.py Python-3.12.1/Lib/test/_test_multiprocessing.py
1248 81,82c81,82
1249 < if support.check_sanitizer(address=True):
1250 < # bpo-45200: Skip multiprocessing tests if Python is built with ASAN to
1251 ---
1252 > if support.HAVE_ASAN_FORK_BUG:
1253 > # gh-89363: Skip multiprocessing tests if Python is built with ASAN to
1254 84c84,89
1255 < raise unittest.SkipTest("libasan has a pthread_create() dead lock")
1256 ---
1257 > raise unittest.SkipTest("libasan has a pthread_create() dead lock related to thread+fork")
1258 >
1259 >
1260 > # gh-110666: Tolerate a difference of 100 ms when comparing timings
1261 > # (clock resolution)
1262 > CLOCK_RES = 0.100
1263 560,561c565
1264 < if os.name != 'nt':
1265 < self.assertEqual(exitcode, -signal.SIGTERM)
1266 ---
1267 > self.assertEqual(exitcode, -signal.SIGTERM)
1268 566a571,572
1269 > else:
1270 > self.assertEqual(exitcode, -signal.SIGTERM)
1271 1653c1659
1272 < expected = 0.1
1273 ---
1274 > expected = 0.100
1275 1657,1658c1663
1276 < # borrow logic in assertTimeout() from test/lock_tests.py
1277 < if not result and expected * 0.6 < dt < expected * 10.0:
1278 ---
1279 > if not result and (expected - CLOCK_RES) <= dt:
1280 1677c1682
1281 < time.sleep(0.01)
1282 ---
1283 > time.sleep(0.010)
1284 2436,2437c2441,2445
1285 < def sqr(x, wait=0.0):
1286 < time.sleep(wait)
1287 ---
1288 > def sqr(x, wait=0.0, event=None):
1289 > if event is None:
1290 > time.sleep(wait)
1291 > else:
1292 > event.wait(wait)
1293 2576,2579c2584,2595
1294 < res = self.pool.apply_async(sqr, (6, TIMEOUT2 + 1.0))
1295 < get = TimingWrapper(res.get)
1296 < self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
1297 < self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
1298 ---
1299 > p = self.Pool(3)
1300 > try:
1301 > event = threading.Event() if self.TYPE == 'threads' else None
1302 > res = p.apply_async(sqr, (6, TIMEOUT2 + support.SHORT_TIMEOUT, event))
1303 > get = TimingWrapper(res.get)
1304 > self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
1305 > self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
1306 > finally:
1307 > if event is not None:
1308 > event.set()
1309 > p.terminate()
1310 > p.join()
1311 2680,2687c2696,2701
1312 < result = self.pool.map_async(
1313 < time.sleep, [0.1 for i in range(10000)], chunksize=1
1314 < )
1315 < self.pool.terminate()
1316 < join = TimingWrapper(self.pool.join)
1317 < join()
1318 < # Sanity check the pool didn't wait for all tasks to finish
1319 < self.assertLess(join.elapsed, 2.0)
1320 ---
1321 > # Simulate slow tasks which take "forever" to complete
1322 > p = self.Pool(3)
1323 > args = [support.LONG_TIMEOUT for i in range(10_000)]
1324 > result = p.map_async(time.sleep, args, chunksize=1)
1325 > p.terminate()
1326 > p.join()
1327 4872c4886
1328 < time.sleep(random.random()*0.1)
1329 ---
1330 > time.sleep(random.random() * 0.100)
1331 4912c4926
1332 < time.sleep(random.random()*0.1)
1333 ---
1334 > time.sleep(random.random() * 0.100)
1335 4961c4975
1336 < expected = 5
1337 ---
1338 > timeout = 5.0 # seconds
1339 4965c4979
1340 < res = wait([a, b], expected)
1341 ---
1342 > res = wait([a, b], timeout)
1343 4969,4970c4983
1344 < self.assertLess(delta, expected * 2)
1345 < self.assertGreater(delta, expected * 0.5)
1346 ---
1347 > self.assertGreater(delta, timeout - CLOCK_RES)
1348 4973,4974d4985
1349 <
1350 < start = time.monotonic()
1351 4976,4977d4986
1352 < delta = time.monotonic() - start
1353 <
1354 4979d4987
1355 < self.assertLess(delta, 0.4)
1356 5437c5445,5447
1357 < self.assertEqual(results, [2, 1])
1358 ---
1359 > # gh-109706: queue.put(1) can write into the queue before queue.put(2),
1360 > # there is no synchronization in the test.
1361 > self.assertSetEqual(set(results), set([2, 1]))
1362 # ----------------------------------------------------------------------
1363 diff Python-3.12.1/Lib/multiprocessing/managers.py Python-3.12.2/Lib/multiprocessing/managers.py
1364 156c156
1365 < self.listener = Listener(address=address, backlog=16)
1366 ---
1367 > self.listener = Listener(address=address, backlog=128)
1368 diff Python-3.12.1/Lib/multiprocessing/popen_spawn_win32.py Python-3.12.2/Lib/multiprocessing/popen_spawn_win32.py
1369 104,115c104,117
1370 < if self.returncode is None:
1371 < if timeout is None:
1372 < msecs = _winapi.INFINITE
1373 < else:
1374 < msecs = max(0, int(timeout * 1000 + 0.5))
1375 <
1376 < res = _winapi.WaitForSingleObject(int(self._handle), msecs)
1377 < if res == _winapi.WAIT_OBJECT_0:
1378 < code = _winapi.GetExitCodeProcess(self._handle)
1379 < if code == TERMINATE:
1380 < code = -signal.SIGTERM
1381 < self.returncode = code
1382 ---
1383 > if self.returncode is not None:
1384 > return self.returncode
1385 >
1386 > if timeout is None:
1387 > msecs = _winapi.INFINITE
1388 > else:
1389 > msecs = max(0, int(timeout * 1000 + 0.5))
1390 >
1391 > res = _winapi.WaitForSingleObject(int(self._handle), msecs)
1392 > if res == _winapi.WAIT_OBJECT_0:
1393 > code = _winapi.GetExitCodeProcess(self._handle)
1394 > if code == TERMINATE:
1395 > code = -signal.SIGTERM
1396 > self.returncode = code
1397 123,134c125,140
1398 < if self.returncode is None:
1399 < try:
1400 < _winapi.TerminateProcess(int(self._handle), TERMINATE)
1401 < except PermissionError:
1402 < # ERROR_ACCESS_DENIED (winerror 5) is received when the
1403 < # process already died.
1404 < code = _winapi.GetExitCodeProcess(int(self._handle))
1405 < if code == _winapi.STILL_ACTIVE:
1406 < raise
1407 < self.returncode = code
1408 < else:
1409 < self.returncode = -signal.SIGTERM
1410 ---
1411 > if self.returncode is not None:
1412 > return
1413 >
1414 > try:
1415 > _winapi.TerminateProcess(int(self._handle), TERMINATE)
1416 > except PermissionError:
1417 > # ERROR_ACCESS_DENIED (winerror 5) is received when the
1418 > # process already died.
1419 > code = _winapi.GetExitCodeProcess(int(self._handle))
1420 > if code == _winapi.STILL_ACTIVE:
1421 > raise
1422 >
1423 > # gh-113009: Don't set self.returncode. Even if GetExitCodeProcess()
1424 > # returns an exit code different than STILL_ACTIVE, the process can
1425 > # still be running. Only set self.returncode once WaitForSingleObject()
1426 > # returns WAIT_OBJECT_0 in wait().
1427 diff Python-3.12.1/Lib/multiprocessing/queues.py Python-3.12.2/Lib/multiprocessing/queues.py
1428 166a167,171
1429 > # gh-107219: Close the connection writer which can unblock
1430 > # Queue._feed() if it was stuck in send_bytes().
1431 > if sys.platform == 'win32':
1432 > self._writer.close()
1433 >
1434 diff Python-3.12.1/Lib/multiprocessing/resource_sharer.py Python-3.12.2/Lib/multiprocessing/resource_sharer.py
1435 126c126
1436 < self._listener = Listener(authkey=process.current_process().authkey)
1437 ---
1438 > self._listener = Listener(authkey=process.current_process().authkey, backlog=128)
1439 diff Python-3.12.1/Lib/multiprocessing/util.py Python-3.12.2/Lib/multiprocessing/util.py
1440 46c46
1441 < _logger.log(SUBDEBUG, msg, *args)
1442 ---
1443 > _logger.log(SUBDEBUG, msg, *args, stacklevel=2)
1444 50c50
1445 < _logger.log(DEBUG, msg, *args)
1446 ---
1447 > _logger.log(DEBUG, msg, *args, stacklevel=2)
1448 54c54
1449 < _logger.log(INFO, msg, *args)
1450 ---
1451 > _logger.log(INFO, msg, *args, stacklevel=2)
1452 58c58
1453 < _logger.log(SUBWARNING, msg, *args)
1454 ---
1455 > _logger.log(SUBWARNING, msg, *args, stacklevel=2)
1456 133c133,136
1457 < rmtree(tempdir)
1458 ---
1459 > def onerror(func, path, err_info):
1460 > if not issubclass(err_info[0], FileNotFoundError):
1461 > raise
1462 > rmtree(tempdir, onerror=onerror)
1463 diff Python-3.12.1/Lib/test/_test_multiprocessing.py Python-3.12.2/Lib/test/_test_multiprocessing.py
1464 2696a2697,2704
1465 > sleep_time = support.LONG_TIMEOUT
1466 >
1467 > if self.TYPE == 'threads':
1468 > # Thread pool workers can't be forced to quit, so if the first
1469 > # task starts early enough, we will end up waiting for it.
1470 > # Sleep for a shorter time, so the test doesn't block.
1471 > sleep_time = 1
1472 >
1473 2698c2706
1474 < args = [support.LONG_TIMEOUT for i in range(10_000)]
1475 ---
1476 > args = [sleep_time for i in range(10_000)]
1477 2699a2708
1478 > time.sleep(0.2) # give some tasks a chance to start
1479 4632a4642,4664
1480 > def test_filename(self):
1481 > logger = multiprocessing.get_logger()
1482 > original_level = logger.level
1483 > try:
1484 > logger.setLevel(util.DEBUG)
1485 > stream = io.StringIO()
1486 > handler = logging.StreamHandler(stream)
1487 > logging_format = '[%(levelname)s] [%(filename)s] %(message)s'
1488 > handler.setFormatter(logging.Formatter(logging_format))
1489 > logger.addHandler(handler)
1490 > logger.info('1')
1491 > util.info('2')
1492 > logger.debug('3')
1493 > filename = os.path.basename(__file__)
1494 > log_record = stream.getvalue()
1495 > self.assertIn(f'[INFO] [{filename}] 1', log_record)
1496 > self.assertIn(f'[INFO] [{filename}] 2', log_record)
1497 > self.assertIn(f'[DEBUG] [{filename}] 3', log_record)
1498 > finally:
1499 > logger.setLevel(original_level)
1500 > logger.removeHandler(handler)
1501 > handler.close()
1502 >
1503 # ----------------------------------------------------------------------
1504 diff Python-3.12.2/Modules/_multiprocessing/posixshmem.c Python-3.12.3/Modules/_multiprocessing/posixshmem.c
1505 45c45,46
1506 < const char *name = PyUnicode_AsUTF8(path);
1507 ---
1508 > Py_ssize_t name_size;
1509 > const char *name = PyUnicode_AsUTF8AndSize(path, &name_size);
1510 48a50,53
1511 > if (strlen(name) != (size_t)name_size) {
1512 > PyErr_SetString(PyExc_ValueError, "embedded null character");
1513 > return -1;
1514 > }
1515 84c89,90
1516 < const char *name = PyUnicode_AsUTF8(path);
1517 ---
1518 > Py_ssize_t name_size;
1519 > const char *name = PyUnicode_AsUTF8AndSize(path, &name_size);
1520 87a94,97
1521 > if (strlen(name) != (size_t)name_size) {
1522 > PyErr_SetString(PyExc_ValueError, "embedded null character");
1523 > return NULL;
1524 > }
1525 diff Python-3.12.2/Lib/multiprocessing/connection.py Python-3.12.3/Lib/multiprocessing/connection.py
1526 478a479
1527 >
1528 480c481
1529 < if self._authkey:
1530 ---
1531 > if self._authkey is not None:
1532 diff Python-3.12.2/Lib/test/_test_multiprocessing.py Python-3.12.3/Lib/test/_test_multiprocessing.py
1533 3468a3469,3492
1534 > def test_empty_authkey(self):
1535 > # bpo-43952: allow empty bytes as authkey
1536 > def handler(*args):
1537 > raise RuntimeError('Connection took too long...')
1538 >
1539 > def run(addr, authkey):
1540 > client = self.connection.Client(addr, authkey=authkey)
1541 > client.send(1729)
1542 >
1543 > key = b''
1544 >
1545 > with self.connection.Listener(authkey=key) as listener:
1546 > thread = threading.Thread(target=run, args=(listener.address, key))
1547 > thread.start()
1548 > try:
1549 > with listener.accept() as d:
1550 > self.assertEqual(d.recv(), 1729)
1551 > finally:
1552 > thread.join()
1553 >
1554 > if self.TYPE == 'processes':
1555 > with self.assertRaises(OSError):
1556 > listener.accept()
1557 >
1558 3935a3960,3974
1559 > def test_shared_memory_name_with_embedded_null(self):
1560 > name_tsmb = self._new_shm_name('test01_null')
1561 > sms = shared_memory.SharedMemory(name_tsmb, create=True, size=512)
1562 > self.addCleanup(sms.unlink)
1563 > with self.assertRaises(ValueError):
1564 > shared_memory.SharedMemory(name_tsmb + '\0a', create=False, size=512)
1565 > if shared_memory._USE_POSIX:
1566 > orig_name = sms._name
1567 > try:
1568 > sms._name = orig_name + '\0a'
1569 > with self.assertRaises(ValueError):
1570 > sms.unlink()
1571 > finally:
1572 > sms._name = orig_name
1573 >
1574 4070c4109
1575 < def test_invalid_shared_memory_cration(self):
1576 ---
1577 > def test_invalid_shared_memory_creation(self):
1578 # ----------------------------------------------------------------------
1579 diff Python-3.12.3/Lib/test/_test_multiprocessing.py Python-3.12.5/Lib/test/_test_multiprocessing.py
1580 25d24
1581 < import pathlib
1582 327,328c326,328
1583 < sys.executable.encode(), # bytes
1584 < pathlib.Path(sys.executable) # os.PathLike
1585 ---
1586 > os.fsencode(sys.executable), # bytes
1587 > os_helper.FakePath(sys.executable), # os.PathLike
1588 > os_helper.FakePath(os.fsencode(sys.executable)), # os.PathLike bytes
1589 1334a1335,1351
1590 > def test_closed_queue_empty_exceptions(self):
1591 > # Assert that checking the emptiness of an unused closed queue
1592 > # does not raise an OSError. The rationale is that q.close() is
1593 > # a no-op upon construction and becomes effective once the queue
1594 > # has been used (e.g., by calling q.put()).
1595 > for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
1596 > q.close() # this is a no-op since the feeder thread is None
1597 > q.join_thread() # this is also a no-op
1598 > self.assertTrue(q.empty())
1599 >
1600 > for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
1601 > q.put('foo') # make sure that the queue is 'used'
1602 > q.close() # close the feeder thread
1603 > q.join_thread() # make sure to join the feeder thread
1604 > with self.assertRaisesRegex(OSError, 'is closed'):
1605 > q.empty()
1606 >
1607 5693a5711,5719
1608 > def test_empty_exceptions(self):
1609 > # Assert that checking emptiness of a closed queue raises
1610 > # an OSError, independently of whether the queue was used
1611 > # or not. This differs from Queue and JoinableQueue.
1612 > q = multiprocessing.SimpleQueue()
1613 > q.close() # close the pipe
1614 > with self.assertRaisesRegex(OSError, 'is closed'):
1615 > q.empty()
1616 >
1617 # ----------------------------------------------------------------------
1618 diff Python-3.12.5/Lib/multiprocessing/connection.py Python-3.12.8/Lib/multiprocessing/connection.py
1619 959c959
1620 < raise AuthenticationError('challenge too short: {len(message)} bytes')
1621 ---
1622 > raise AuthenticationError(f'challenge too short: {len(message)} bytes')
1623 diff Python-3.12.5/Lib/multiprocessing/forkserver.py Python-3.12.8/Lib/multiprocessing/forkserver.py
1624 169a170,171
1625 > if sys_path is not None:
1626 > sys.path[:] = sys_path
1627 diff Python-3.12.5/Lib/multiprocessing/managers.py Python-3.12.8/Lib/multiprocessing/managers.py
1628 757a758,761
1629 > # Each instance gets a `_serial` number. Unlike `id(...)`, this number
1630 > # is never reused.
1631 > _next_serial = 1
1632 >
1633 761,764c765,771
1634 < tls_idset = BaseProxy._address_to_local.get(token.address, None)
1635 < if tls_idset is None:
1636 < tls_idset = util.ForkAwareLocal(), ProcessLocalSet()
1637 < BaseProxy._address_to_local[token.address] = tls_idset
1638 ---
1639 > tls_serials = BaseProxy._address_to_local.get(token.address, None)
1640 > if tls_serials is None:
1641 > tls_serials = util.ForkAwareLocal(), ProcessLocalSet()
1642 > BaseProxy._address_to_local[token.address] = tls_serials
1643 >
1644 > self._serial = BaseProxy._next_serial
1645 > BaseProxy._next_serial += 1
1646 768c775
1647 < self._tls = tls_idset[0]
1648 ---
1649 > self._tls = tls_serials[0]
1650 770,771c777,778
1651 < # self._idset is used to record the identities of all shared
1652 < # objects for which the current process owns references and
1653 ---
1654 > # self._all_serials is a set used to record the identities of all
1655 > # shared objects for which the current process owns references and
1656 773c780
1657 < self._idset = tls_idset[1]
1658 ---
1659 > self._all_serials = tls_serials[1]
1660 853c860
1661 < self._idset.add(self._id)
1662 ---
1663 > self._all_serials.add(self._serial)
1664 859,860c866,867
1665 < args=(self._token, self._authkey, state,
1666 < self._tls, self._idset, self._Client),
1667 ---
1668 > args=(self._token, self._serial, self._authkey, state,
1669 > self._tls, self._all_serials, self._Client),
1670 865,866c872,873
1671 < def _decref(token, authkey, state, tls, idset, _Client):
1672 < idset.discard(token.id)
1673 ---
1674 > def _decref(token, serial, authkey, state, tls, idset, _Client):
1675 > idset.discard(serial)
1676 diff Python-3.12.5/Lib/multiprocessing/synchronize.py Python-3.12.8/Lib/multiprocessing/synchronize.py
1677 177c177
1678 < elif self._semlock._get_value() == 1:
1679 ---
1680 > elif not self._semlock._is_zero():
1681 203c203
1682 < elif self._semlock._get_value() == 1:
1683 ---
1684 > elif not self._semlock._is_zero():
1685 diff Python-3.12.5/Lib/test/_test_multiprocessing.py Python-3.12.8/Lib/test/_test_multiprocessing.py
1686 14a15
1687 > import importlib
1688 21a23
1689 > import shutil
1690 23a26
1691 > import tempfile
1692 256a260,262
1693 > # If not empty, limit which start method suites run this class.
1694 > START_METHODS: set[str] = set()
1695 > start_method = None # set by install_tests_in_module_dict()
1696 1364a1371,1430
1697 > @staticmethod
1698 > def _acquire(lock, l=None):
1699 > lock.acquire()
1700 > if l is not None:
1701 > l.append(repr(lock))
1702 >
1703 > @staticmethod
1704 > def _acquire_event(lock, event):
1705 > lock.acquire()
1706 > event.set()
1707 > time.sleep(1.0)
1708 >
1709 > def test_repr_lock(self):
1710 > if self.TYPE != 'processes':
1711 > self.skipTest('test not appropriate for {}'.format(self.TYPE))
1712 >
1713 > lock = self.Lock()
1714 > self.assertEqual(f'<Lock(owner=None)>', repr(lock))
1715 >
1716 > lock.acquire()
1717 > self.assertEqual(f'<Lock(owner=MainProcess)>', repr(lock))
1718 > lock.release()
1719 >
1720 > tname = 'T1'
1721 > l = []
1722 > t = threading.Thread(target=self._acquire,
1723 > args=(lock, l),
1724 > name=tname)
1725 > t.start()
1726 > time.sleep(0.1)
1727 > self.assertEqual(f'<Lock(owner=MainProcess|{tname})>', l[0])
1728 > lock.release()
1729 >
1730 > t = threading.Thread(target=self._acquire,
1731 > args=(lock,),
1732 > name=tname)
1733 > t.start()
1734 > time.sleep(0.1)
1735 > self.assertEqual('<Lock(owner=SomeOtherThread)>', repr(lock))
1736 > lock.release()
1737 >
1738 > pname = 'P1'
1739 > l = multiprocessing.Manager().list()
1740 > p = self.Process(target=self._acquire,
1741 > args=(lock, l),
1742 > name=pname)
1743 > p.start()
1744 > p.join()
1745 > self.assertEqual(f'<Lock(owner={pname})>', l[0])
1746 >
1747 > lock = self.Lock()
1748 > event = self.Event()
1749 > p = self.Process(target=self._acquire_event,
1750 > args=(lock, event),
1751 > name='P2')
1752 > p.start()
1753 > event.wait()
1754 > self.assertEqual(f'<Lock(owner=SomeOtherProcess)>', repr(lock))
1755 > p.terminate()
1756 >
1757 1371a1438,1499
1758 > @staticmethod
1759 > def _acquire_release(lock, timeout, l=None, n=1):
1760 > for _ in range(n):
1761 > lock.acquire()
1762 > if l is not None:
1763 > l.append(repr(lock))
1764 > time.sleep(timeout)
1765 > for _ in range(n):
1766 > lock.release()
1767 >
1768 > def test_repr_rlock(self):
1769 > if self.TYPE != 'processes':
1770 > self.skipTest('test not appropriate for {}'.format(self.TYPE))
1771 >
1772 > lock = self.RLock()
1773 > self.assertEqual('<RLock(None, 0)>', repr(lock))
1774 >
1775 > n = 3
1776 > for _ in range(n):
1777 > lock.acquire()
1778 > self.assertEqual(f'<RLock(MainProcess, {n})>', repr(lock))
1779 > for _ in range(n):
1780 > lock.release()
1781 >
1782 > t, l = [], []
1783 > for i in range(n):
1784 > t.append(threading.Thread(target=self._acquire_release,
1785 > args=(lock, 0.1, l, i+1),
1786 > name=f'T{i+1}'))
1787 > t[-1].start()
1788 > for t_ in t:
1789 > t_.join()
1790 > for i in range(n):
1791 > self.assertIn(f'<RLock(MainProcess|T{i+1}, {i+1})>', l)
1792 >
1793 >
1794 > t = threading.Thread(target=self._acquire_release,
1795 > args=(lock, 0.2),
1796 > name=f'T1')
1797 > t.start()
1798 > time.sleep(0.1)
1799 > self.assertEqual('<RLock(SomeOtherThread, nonzero)>', repr(lock))
1800 > time.sleep(0.2)
1801 >
1802 > pname = 'P1'
1803 > l = multiprocessing.Manager().list()
1804 > p = self.Process(target=self._acquire_release,
1805 > args=(lock, 0.1, l),
1806 > name=pname)
1807 > p.start()
1808 > p.join()
1809 > self.assertEqual(f'<RLock({pname}, 1)>', l[0])
1810 >
1811 > event = self.Event()
1812 > lock = self.RLock()
1813 > p = self.Process(target=self._acquire_event,
1814 > args=(lock, event))
1815 > p.start()
1816 > event.wait()
1817 > self.assertEqual('<RLock(SomeOtherProcess, nonzero)>', repr(lock))
1818 > p.join()
1819 >
1820 5657a5786,5787
1821 > @unittest.skipIf(sys.platform.startswith("netbsd"),
1822 > "gh-125620: Skip on NetBSD due to long wait for SIGKILL process termination.")
1823 6065a6196,6265
1824 > class _TestSpawnedSysPath(BaseTestCase):
1825 > """Test that sys.path is setup in forkserver and spawn processes."""
1826 >
1827 > ALLOWED_TYPES = {'processes'}
1828 > # Not applicable to fork which inherits everything from the process as is.
1829 > START_METHODS = {"forkserver", "spawn"}
1830 >
1831 > def setUp(self):
1832 > self._orig_sys_path = list(sys.path)
1833 > self._temp_dir = tempfile.mkdtemp(prefix="test_sys_path-")
1834 > self._mod_name = "unique_test_mod"
1835 > module_path = os.path.join(self._temp_dir, f"{self._mod_name}.py")
1836 > with open(module_path, "w", encoding="utf-8") as mod:
1837 > mod.write("# A simple test module\n")
1838 > sys.path[:] = [p for p in sys.path if p] # remove any existing ""s
1839 > sys.path.insert(0, self._temp_dir)
1840 > sys.path.insert(0, "") # Replaced with an abspath in child.
1841 > self.assertIn(self.start_method, self.START_METHODS)
1842 > self._ctx = multiprocessing.get_context(self.start_method)
1843 >
1844 > def tearDown(self):
1845 > sys.path[:] = self._orig_sys_path
1846 > shutil.rmtree(self._temp_dir, ignore_errors=True)
1847 >
1848 > @staticmethod
1849 > def enq_imported_module_names(queue):
1850 > queue.put(tuple(sys.modules))
1851 >
1852 > def test_forkserver_preload_imports_sys_path(self):
1853 > if self._ctx.get_start_method() != "forkserver":
1854 > self.skipTest("forkserver specific test.")
1855 > self.assertNotIn(self._mod_name, sys.modules)
1856 > multiprocessing.forkserver._forkserver._stop() # Must be fresh.
1857 > self._ctx.set_forkserver_preload(
1858 > ["test.test_multiprocessing_forkserver", self._mod_name])
1859 > q = self._ctx.Queue()
1860 > proc = self._ctx.Process(
1861 > target=self.enq_imported_module_names, args=(q,))
1862 > proc.start()
1863 > proc.join()
1864 > child_imported_modules = q.get()
1865 > q.close()
1866 > self.assertIn(self._mod_name, child_imported_modules)
1867 >
1868 > @staticmethod
1869 > def enq_sys_path_and_import(queue, mod_name):
1870 > queue.put(sys.path)
1871 > try:
1872 > importlib.import_module(mod_name)
1873 > except ImportError as exc:
1874 > queue.put(exc)
1875 > else:
1876 > queue.put(None)
1877 >
1878 > def test_child_sys_path(self):
1879 > q = self._ctx.Queue()
1880 > proc = self._ctx.Process(
1881 > target=self.enq_sys_path_and_import, args=(q, self._mod_name))
1882 > proc.start()
1883 > proc.join()
1884 > child_sys_path = q.get()
1885 > import_error = q.get()
1886 > q.close()
1887 > self.assertNotIn("", child_sys_path) # replaced by an abspath
1888 > self.assertIn(self._temp_dir, child_sys_path) # our addition
1889 > # ignore the first element, it is the absolute "" replacement
1890 > self.assertEqual(child_sys_path[1:], sys.path[1:])
1891 > self.assertIsNone(import_error, msg=f"child could not import {self._mod_name}")
1892 >
1893 >
1894 6241a6442,6443
1895 > if base.START_METHODS and start_method not in base.START_METHODS:
1896 > continue # class not intended for this start method.
1897 6254a6457
1898 > Temp.start_method = start_method
1899 # ----------------------------------------------------------------------
1900 diff Python-3.12.8/Modules/_multiprocessing/semaphore.c Python-3.12.9/Modules/_multiprocessing/semaphore.c
1901 25a26,27
1902 > #define _SemLockObject_CAST(op) ((SemLockObject *)(op))
1903 >
1904 570c572
1905 < semlock_dealloc(SemLockObject* self)
1906 ---
1907 > semlock_dealloc(PyObject *op)
1908 571a574
1909 > SemLockObject *self = _SemLockObject_CAST(op);
1910 709c712
1911 < semlock_traverse(SemLockObject *s, visitproc visit, void *arg)
1912 ---
1913 > semlock_traverse(PyObject *s, visitproc visit, void *arg)
1914 diff Python-3.12.8/Lib/multiprocessing/connection.py Python-3.12.9/Lib/multiprocessing/connection.py
1915 849c849
1916 < def _get_digest_name_and_payload(message: bytes) -> (str, bytes):
1917 ---
1918 > def _get_digest_name_and_payload(message): # type: (bytes) -> tuple[str, bytes]
1919 diff Python-3.12.8/Lib/multiprocessing/resource_tracker.py Python-3.12.9/Lib/multiprocessing/resource_tracker.py
1920 144a145
1921 > prev_sigmask = None
1922 147c148
1923 < signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
1924 ---
1925 > prev_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, _IGNORED_SIGNALS)
1926 150,151c151,152
1927 < if _HAVE_SIGMASK:
1928 < signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
1929 ---
1930 > if prev_sigmask is not None:
1931 > signal.pthread_sigmask(signal.SIG_SETMASK, prev_sigmask)
1932 diff Python-3.12.8/Lib/multiprocessing/synchronize.py Python-3.12.9/Lib/multiprocessing/synchronize.py
1933 363c363
1934 < def __repr__(self) -> str:
1935 ---
1936 > def __repr__(self):
1937 diff Python-3.12.8/Lib/test/_test_multiprocessing.py Python-3.12.9/Lib/test/_test_multiprocessing.py
1938 5828a5829,5849
1939 > @unittest.skipUnless(hasattr(signal, "pthread_sigmask"), "pthread_sigmask is not available")
1940 > def test_resource_tracker_blocked_signals(self):
1941 > #
1942 > # gh-127586: Check that resource_tracker does not override blocked signals of caller.
1943 > #
1944 > from multiprocessing.resource_tracker import ResourceTracker
1945 > orig_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, set())
1946 > signals = {signal.SIGTERM, signal.SIGINT, signal.SIGUSR1}
1947 >
1948 > try:
1949 > for sig in signals:
1950 > signal.pthread_sigmask(signal.SIG_SETMASK, {sig})
1951 > self.assertEqual(signal.pthread_sigmask(signal.SIG_BLOCK, set()), {sig})
1952 > tracker = ResourceTracker()
1953 > tracker.ensure_running()
1954 > self.assertEqual(signal.pthread_sigmask(signal.SIG_BLOCK, set()), {sig})
1955 > tracker._stop()
1956 > finally:
1957 > # restore sigmask to what it was before executing test
1958 > signal.pthread_sigmask(signal.SIG_SETMASK, orig_sigmask)
1959 >
1960 # ----------------------------------------------------------------------
1961 diff Python-3.12.9/Lib/multiprocessing/resource_tracker.py Python-3.12.10/Lib/multiprocessing/resource_tracker.py
1962 73,85c73,109
1963 < def _stop(self):
1964 < with self._lock:
1965 < # This should not happen (_stop() isn't called by a finalizer)
1966 < # but we check for it anyway.
1967 < if self._lock._recursion_count() > 1:
1968 < return self._reentrant_call_error()
1969 < if self._fd is None:
1970 < # not running
1971 < return
1972 <
1973 < # closing the "alive" file descriptor stops main()
1974 < os.close(self._fd)
1975 < self._fd = None
1976 ---
1977 > def __del__(self):
1978 > # making sure child processess are cleaned before ResourceTracker
1979 > # gets destructed.
1980 > # see https://github.com/python/cpython/issues/88887
1981 > self._stop(use_blocking_lock=False)
1982 >
1983 > def _stop(self, use_blocking_lock=True):
1984 > if use_blocking_lock:
1985 > with self._lock:
1986 > self._stop_locked()
1987 > else:
1988 > acquired = self._lock.acquire(blocking=False)
1989 > try:
1990 > self._stop_locked()
1991 > finally:
1992 > if acquired:
1993 > self._lock.release()
1994 >
1995 > def _stop_locked(
1996 > self,
1997 > close=os.close,
1998 > waitpid=os.waitpid,
1999 > waitstatus_to_exitcode=os.waitstatus_to_exitcode,
2000 > ):
2001 > # This shouldn't happen (it might when called by a finalizer)
2002 > # so we check for it anyway.
2003 > if self._lock._recursion_count() > 1:
2004 > return self._reentrant_call_error()
2005 > if self._fd is None:
2006 > # not running
2007 > return
2008 > if self._pid is None:
2009 > return
2010 >
2011 > # closing the "alive" file descriptor stops main()
2012 > close(self._fd)
2013 > self._fd = None
2014 87,88c111,112
2015 < os.waitpid(self._pid, 0)
2016 < self._pid = None
2017 ---
2018 > waitpid(self._pid, 0)
2019 > self._pid = None
2020 diff Python-3.12.9/Lib/test/_test_multiprocessing.py Python-3.12.10/Lib/test/_test_multiprocessing.py
2021 591c591,592
2022 < p = self.Process(target=time.sleep, args=(DELTA,))
2023 ---
2024 > event = self.Event()
2025 > p = self.Process(target=event.wait, args=())
2026 594,596c595,600
2027 < p.daemon = True
2028 < p.start()
2029 < self.assertIn(p, self.active_children())
2030 ---
2031 > try:
2032 > p.daemon = True
2033 > p.start()
2034 > self.assertIn(p, self.active_children())
2035 > finally:
2036 > event.set()
2037 1580c1584
2038 < for i in range(10):
2039 ---
2040 > for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
2041 1586,1587c1590
2042 < time.sleep(DELTA)
2043 < time.sleep(DELTA)
2044 ---
2045 >
2046 1609d1611
2047 < self.addCleanup(p.join)
2048 1611,1614c1613,1615
2049 < p = threading.Thread(target=self.f, args=(cond, sleeping, woken))
2050 < p.daemon = True
2051 < p.start()
2052 < self.addCleanup(p.join)
2053 ---
2054 > t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
2055 > t.daemon = True
2056 > t.start()
2057 1621,1622c1622
2058 < time.sleep(DELTA)
2059 < self.assertReturnsIfImplemented(0, get_value, woken)
2060 ---
2061 > self.assertReachesEventually(lambda: get_value(woken), 0)
2062 1630,1631c1630
2063 < time.sleep(DELTA)
2064 < self.assertReturnsIfImplemented(1, get_value, woken)
2065 ---
2066 > self.assertReachesEventually(lambda: get_value(woken), 1)
2067 1639,1640c1638
2068 < time.sleep(DELTA)
2069 < self.assertReturnsIfImplemented(2, get_value, woken)
2070 ---
2071 > self.assertReachesEventually(lambda: get_value(woken), 2)
2072 1644c1642,1644
2073 < p.join()
2074 ---
2075 >
2076 > threading_helper.join_thread(t)
2077 > join_process(p)
2078 1651a1652
2079 > workers = []
2080 1657c1658
2081 < self.addCleanup(p.join)
2082 ---
2083 > workers.append(p)
2084 1663c1664
2085 < self.addCleanup(t.join)
2086 ---
2087 > workers.append(t)
2088 1682c1683
2089 < self.addCleanup(p.join)
2090 ---
2091 > workers.append(p)
2092 1687c1688
2093 < self.addCleanup(t.join)
2094 ---
2095 > workers.append(t)
2096 1703c1704,1706
2097 < self.assertReachesEventually(lambda: get_value(woken), 6)
2098 ---
2099 > for i in range(6):
2100 > woken.acquire()
2101 > self.assertReturnsIfImplemented(0, get_value, woken)
2102 1707a1711,1714
2103 > for w in workers:
2104 > # NOTE: join_process and join_thread are the same
2105 > threading_helper.join_thread(w)
2106 >
2107 1713a1721
2108 > workers = []
2109 1718c1726
2110 < self.addCleanup(p.join)
2111 ---
2112 > workers.append(p)
2113 1723c1731
2114 < self.addCleanup(t.join)
2115 ---
2116 > workers.append(t)
2117 1757a1766,1769
2118 > for w in workers:
2119 > # NOTE: join_process and join_thread are the same
2120 > threading_helper.join_thread(w)
2121 >