Debian Codegraph @

Lib/test/_test_multiprocessing.py

raw
1 #
2 # Unit tests for the multiprocessing package
3 #
4
5 import unittest
6 import unittest.mock
7 import queue as pyqueue
8 import textwrap
9 import time
10 import io
11 import itertools
12 import sys
13 import os
14 import gc
15 import importlib
16 import errno
17 import functools
18 import signal
19 import array
20 import socket
21 import random
22 import logging
23 import shutil
24 import subprocess
25 import struct
26 import tempfile
27 import operator
28 import pickle
29 import weakref
30 import warnings
31 import test.support
32 import test.support.script_helper
33 from test import support
34 from test.support import hashlib_helper
35 from test.support import import_helper
36 from test.support import os_helper
37 from test.support import script_helper
38 from test.support import socket_helper
39 from test.support import threading_helper
40 from test.support import warnings_helper
41 from test.support import subTests
42
43 # Skip tests if _multiprocessing wasn't built.
44 _multiprocessing = import_helper.import_module('_multiprocessing')
45 # Skip tests if sem_open implementation is broken.
46 support.skip_if_broken_multiprocessing_synchronize()
47 import threading
48
49 import multiprocessing.connection
50 import multiprocessing.dummy
51 import multiprocessing.heap
52 import multiprocessing.managers
53 import multiprocessing.pool
54 import multiprocessing.queues
55 from multiprocessing.connection import wait
56
57 from multiprocessing import util
58
59 try:
60 from multiprocessing import reduction
61 HAS_REDUCTION = reduction.HAVE_SEND_HANDLE
62 except ImportError:
63 HAS_REDUCTION = False
64
65 try:
66 from multiprocessing.sharedctypes import Value, copy
67 HAS_SHAREDCTYPES = True
68 except ImportError:
69 HAS_SHAREDCTYPES = False
70
71 try:
72 from multiprocessing import shared_memory
73 HAS_SHMEM = True
74 except ImportError:
75 HAS_SHMEM = False
76
77 try:
78 import msvcrt
79 except ImportError:
80 msvcrt = None
81
82
83 if support.HAVE_ASAN_FORK_BUG:
84 # gh-89363: Skip multiprocessing tests if Python is built with ASAN to
85 # work around a libasan race condition: dead lock in pthread_create().
86 raise unittest.SkipTest("libasan has a pthread_create() dead lock related to thread+fork")
87
88
89 # gh-110666: Tolerate a difference of 100 ms when comparing timings
90 # (clock resolution)
91 CLOCK_RES = 0.100
92
93
94 def latin(s):
95 return s.encode('latin')
96
97
98 def close_queue(queue):
99 if isinstance(queue, multiprocessing.queues.Queue):
100 queue.close()
101 queue.join_thread()
102
103
104 def join_process(process):
105 # Since multiprocessing.Process has the same API than threading.Thread
106 # (join() and is_alive(), the support function can be reused
107 threading_helper.join_thread(process)
108
109
110 if os.name == "posix":
111 from multiprocessing import resource_tracker
112
113 def _resource_unlink(name, rtype):
114 resource_tracker._CLEANUP_FUNCS[rtype](name)
115
116
117 #
118 # Constants
119 #
120
121 LOG_LEVEL = util.SUBWARNING
122 #LOG_LEVEL = logging.DEBUG
123
124 DELTA = 0.1
125 CHECK_TIMINGS = False # making true makes tests take a lot longer
126 # and can sometimes cause some non-serious
127 # failures because some calls block a bit
128 # longer than expected
129 if CHECK_TIMINGS:
130 TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.82, 0.35, 1.4
131 else:
132 TIMEOUT1, TIMEOUT2, TIMEOUT3 = 0.1, 0.1, 0.1
133
134 # BaseManager.shutdown_timeout
135 SHUTDOWN_TIMEOUT = support.SHORT_TIMEOUT
136
137 WAIT_ACTIVE_CHILDREN_TIMEOUT = 5.0
138
139 HAVE_GETVALUE = not getattr(_multiprocessing,
140 'HAVE_BROKEN_SEM_GETVALUE', False)
141
142 WIN32 = (sys.platform == "win32")
143
144 def wait_for_handle(handle, timeout):
145 if timeout is not None and timeout < 0.0:
146 timeout = None
147 return wait([handle], timeout)
148
149 try:
150 MAXFD = os.sysconf("SC_OPEN_MAX")
151 except:
152 MAXFD = 256
153
154 # To speed up tests when using the forkserver, we can preload these:
155 PRELOAD = ['__main__', 'test.test_multiprocessing_forkserver']
156
157 #
158 # Some tests require ctypes
159 #
160
161 try:
162 from ctypes import Structure, c_int, c_double, c_longlong
163 except ImportError:
164 Structure = object
165 c_int = c_double = c_longlong = None
166
167
168 def check_enough_semaphores():
169 """Check that the system supports enough semaphores to run the test."""
170 # minimum number of semaphores available according to POSIX
171 nsems_min = 256
172 try:
173 nsems = os.sysconf("SC_SEM_NSEMS_MAX")
174 except (AttributeError, ValueError):
175 # sysconf not available or setting not available
176 return
177 if nsems == -1 or nsems >= nsems_min:
178 return
179 raise unittest.SkipTest("The OS doesn't support enough semaphores "
180 "to run the test (required: %d)." % nsems_min)
181
182
183 def only_run_in_spawn_testsuite(reason):
184 """Returns a decorator: raises SkipTest when SM != spawn at test time.
185
186 This can be useful to save overall Python test suite execution time.
187 "spawn" is the universal mode available on all platforms so this limits the
188 decorated test to only execute within test_multiprocessing_spawn.
189
190 This would not be necessary if we refactored our test suite to split things
191 into other test files when they are not start method specific to be rerun
192 under all start methods.
193 """
194
195 def decorator(test_item):
196
197 @functools.wraps(test_item)
198 def spawn_check_wrapper(*args, **kwargs):
199 if (start_method := multiprocessing.get_start_method()) != "spawn":
200 raise unittest.SkipTest(f"{start_method=}, not 'spawn'; {reason}")
201 return test_item(*args, **kwargs)
202
203 return spawn_check_wrapper
204
205 return decorator
206
207
208 class TestInternalDecorators(unittest.TestCase):
209 """Logic within a test suite that could errantly skip tests? Test it!"""
210
211 @unittest.skipIf(sys.platform == "win32", "test requires that fork exists.")
212 def test_only_run_in_spawn_testsuite(self):
213 if multiprocessing.get_start_method() != "spawn":
214 raise unittest.SkipTest("only run in test_multiprocessing_spawn.")
215
216 try:
217 @only_run_in_spawn_testsuite("testing this decorator")
218 def return_four_if_spawn():
219 return 4
220 except Exception as err:
221 self.fail(f"expected decorated `def` not to raise; caught {err}")
222
223 orig_start_method = multiprocessing.get_start_method(allow_none=True)
224 try:
225 multiprocessing.set_start_method("spawn", force=True)
226 self.assertEqual(return_four_if_spawn(), 4)
227 multiprocessing.set_start_method("fork", force=True)
228 with self.assertRaises(unittest.SkipTest) as ctx:
229 return_four_if_spawn()
230 self.assertIn("testing this decorator", str(ctx.exception))
231 self.assertIn("start_method=", str(ctx.exception))
232 finally:
233 multiprocessing.set_start_method(orig_start_method, force=True)
234
235
236 #
237 # Creates a wrapper for a function which records the time it takes to finish
238 #
239
240 class TimingWrapper(object):
241
242 def __init__(self, func):
243 self.func = func
244 self.elapsed = None
245
246 def __call__(self, *args, **kwds):
247 t = time.monotonic()
248 try:
249 return self.func(*args, **kwds)
250 finally:
251 self.elapsed = time.monotonic() - t
252
253 #
254 # Base class for test cases
255 #
256
257 class BaseTestCase(object):
258
259 ALLOWED_TYPES = ('processes', 'manager', 'threads')
260 # If not empty, limit which start method suites run this class.
261 START_METHODS: set[str] = set()
262 start_method = None # set by install_tests_in_module_dict()
263
264 def assertTimingAlmostEqual(self, a, b):
265 if CHECK_TIMINGS:
266 self.assertAlmostEqual(a, b, 1)
267
268 def assertReturnsIfImplemented(self, value, func, *args):
269 try:
270 res = func(*args)
271 except NotImplementedError:
272 pass
273 else:
274 return self.assertEqual(value, res)
275
276 # For the sanity of Windows users, rather than crashing or freezing in
277 # multiple ways.
278 def __reduce__(self, *args):
279 raise NotImplementedError("shouldn't try to pickle a test case")
280
281 __reduce_ex__ = __reduce__
282
283 #
284 # Return the value of a semaphore
285 #
286
287 def get_value(self):
288 try:
289 return self.get_value()
290 except AttributeError:
291 try:
292 return self._Semaphore__value
293 except AttributeError:
294 try:
295 return self._value
296 except AttributeError:
297 raise NotImplementedError
298
299 #
300 # Testcases
301 #
302
303 class DummyCallable:
304 def __call__(self, q, c):
305 assert isinstance(c, DummyCallable)
306 q.put(5)
307
308
309 class _TestProcess(BaseTestCase):
310
311 ALLOWED_TYPES = ('processes', 'threads')
312
313 def test_current(self):
314 if self.TYPE == 'threads':
315 self.skipTest('test not appropriate for {}'.format(self.TYPE))
316
317 current = self.current_process()
318 authkey = current.authkey
319
320 self.assertTrue(current.is_alive())
321 self.assertTrue(not current.daemon)
322 self.assertIsInstance(authkey, bytes)
323 self.assertTrue(len(authkey) > 0)
324 self.assertEqual(current.ident, os.getpid())
325 self.assertEqual(current.exitcode, None)
326
327 def test_set_executable(self):
328 if self.TYPE == 'threads':
329 self.skipTest(f'test not appropriate for {self.TYPE}')
330 paths = [
331 sys.executable, # str
332 os.fsencode(sys.executable), # bytes
333 os_helper.FakePath(sys.executable), # os.PathLike
334 os_helper.FakePath(os.fsencode(sys.executable)), # os.PathLike bytes
335 ]
336 for path in paths:
337 self.set_executable(path)
338 p = self.Process()
339 p.start()
340 p.join()
341 self.assertEqual(p.exitcode, 0)
342
343 @support.requires_resource('cpu')
344 def test_args_argument(self):
345 # bpo-45735: Using list or tuple as *args* in constructor could
346 # achieve the same effect.
347 args_cases = (1, "str", [1], (1,))
348 args_types = (list, tuple)
349
350 test_cases = itertools.product(args_cases, args_types)
351
352 for args, args_type in test_cases:
353 with self.subTest(args=args, args_type=args_type):
354 q = self.Queue(1)
355 # pass a tuple or list as args
356 p = self.Process(target=self._test_args, args=args_type((q, args)))
357 p.daemon = True
358 p.start()
359 child_args = q.get()
360 self.assertEqual(child_args, args)
361 p.join()
362 close_queue(q)
363
364 @classmethod
365 def _test_args(cls, q, arg):
366 q.put(arg)
367
368 def test_daemon_argument(self):
369 if self.TYPE == "threads":
370 self.skipTest('test not appropriate for {}'.format(self.TYPE))
371
372 # By default uses the current process's daemon flag.
373 proc0 = self.Process(target=self._test)
374 self.assertEqual(proc0.daemon, self.current_process().daemon)
375 proc1 = self.Process(target=self._test, daemon=True)
376 self.assertTrue(proc1.daemon)
377 proc2 = self.Process(target=self._test, daemon=False)
378 self.assertFalse(proc2.daemon)
379
380 @classmethod
381 def _test(cls, q, *args, **kwds):
382 current = cls.current_process()
383 q.put(args)
384 q.put(kwds)
385 q.put(current.name)
386 if cls.TYPE != 'threads':
387 q.put(bytes(current.authkey))
388 q.put(current.pid)
389
390 def test_parent_process_attributes(self):
391 if self.TYPE == "threads":
392 self.skipTest('test not appropriate for {}'.format(self.TYPE))
393
394 self.assertIsNone(self.parent_process())
395
396 rconn, wconn = self.Pipe(duplex=False)
397 p = self.Process(target=self._test_send_parent_process, args=(wconn,))
398 p.start()
399 p.join()
400 parent_pid, parent_name = rconn.recv()
401 self.assertEqual(parent_pid, self.current_process().pid)
402 self.assertEqual(parent_pid, os.getpid())
403 self.assertEqual(parent_name, self.current_process().name)
404
405 @classmethod
406 def _test_send_parent_process(cls, wconn):
407 from multiprocessing.process import parent_process
408 wconn.send([parent_process().pid, parent_process().name])
409
410 def test_parent_process(self):
411 if self.TYPE == "threads":
412 self.skipTest('test not appropriate for {}'.format(self.TYPE))
413
414 # Launch a child process. Make it launch a grandchild process. Kill the
415 # child process and make sure that the grandchild notices the death of
416 # its parent (a.k.a the child process).
417 rconn, wconn = self.Pipe(duplex=False)
418 p = self.Process(
419 target=self._test_create_grandchild_process, args=(wconn, ))
420 p.start()
421
422 if not rconn.poll(timeout=support.LONG_TIMEOUT):
423 raise AssertionError("Could not communicate with child process")
424 parent_process_status = rconn.recv()
425 self.assertEqual(parent_process_status, "alive")
426
427 p.terminate()
428 p.join()
429
430 if not rconn.poll(timeout=support.LONG_TIMEOUT):
431 raise AssertionError("Could not communicate with child process")
432 parent_process_status = rconn.recv()
433 self.assertEqual(parent_process_status, "not alive")
434
435 @classmethod
436 def _test_create_grandchild_process(cls, wconn):
437 p = cls.Process(target=cls._test_report_parent_status, args=(wconn, ))
438 p.start()
439 time.sleep(300)
440
441 @classmethod
442 def _test_report_parent_status(cls, wconn):
443 from multiprocessing.process import parent_process
444 wconn.send("alive" if parent_process().is_alive() else "not alive")
445 parent_process().join(timeout=support.SHORT_TIMEOUT)
446 wconn.send("alive" if parent_process().is_alive() else "not alive")
447
448 def test_process(self):
449 q = self.Queue(1)
450 e = self.Event()
451 args = (q, 1, 2)
452 kwargs = {'hello':23, 'bye':2.54}
453 name = 'SomeProcess'
454 p = self.Process(
455 target=self._test, args=args, kwargs=kwargs, name=name
456 )
457 p.daemon = True
458 current = self.current_process()
459
460 if self.TYPE != 'threads':
461 self.assertEqual(p.authkey, current.authkey)
462 self.assertEqual(p.is_alive(), False)
463 self.assertEqual(p.daemon, True)
464 self.assertNotIn(p, self.active_children())
465 self.assertTrue(type(self.active_children()) is list)
466 self.assertEqual(p.exitcode, None)
467
468 p.start()
469
470 self.assertEqual(p.exitcode, None)
471 self.assertEqual(p.is_alive(), True)
472 self.assertIn(p, self.active_children())
473
474 self.assertEqual(q.get(), args[1:])
475 self.assertEqual(q.get(), kwargs)
476 self.assertEqual(q.get(), p.name)
477 if self.TYPE != 'threads':
478 self.assertEqual(q.get(), current.authkey)
479 self.assertEqual(q.get(), p.pid)
480
481 p.join()
482
483 self.assertEqual(p.exitcode, 0)
484 self.assertEqual(p.is_alive(), False)
485 self.assertNotIn(p, self.active_children())
486 close_queue(q)
487
488 @unittest.skipUnless(threading._HAVE_THREAD_NATIVE_ID, "needs native_id")
489 def test_process_mainthread_native_id(self):
490 if self.TYPE == 'threads':
491 self.skipTest('test not appropriate for {}'.format(self.TYPE))
492
493 current_mainthread_native_id = threading.main_thread().native_id
494
495 q = self.Queue(1)
496 p = self.Process(target=self._test_process_mainthread_native_id, args=(q,))
497 p.start()
498
499 child_mainthread_native_id = q.get()
500 p.join()
501 close_queue(q)
502
503 self.assertNotEqual(current_mainthread_native_id, child_mainthread_native_id)
504
505 @classmethod
506 def _test_process_mainthread_native_id(cls, q):
507 mainthread_native_id = threading.main_thread().native_id
508 q.put(mainthread_native_id)
509
510 @classmethod
511 def _sleep_some(cls):
512 time.sleep(100)
513
514 @classmethod
515 def _sleep_some_event(cls, event):
516 event.set()
517 time.sleep(100)
518
519 @classmethod
520 def _test_sleep(cls, delay):
521 time.sleep(delay)
522
523 def _kill_process(self, meth):
524 if self.TYPE == 'threads':
525 self.skipTest('test not appropriate for {}'.format(self.TYPE))
526
527 event = self.Event()
528 p = self.Process(target=self._sleep_some_event, args=(event,))
529 p.daemon = True
530 p.start()
531
532 self.assertEqual(p.is_alive(), True)
533 self.assertIn(p, self.active_children())
534 self.assertEqual(p.exitcode, None)
535
536 join = TimingWrapper(p.join)
537
538 self.assertEqual(join(0), None)
539 self.assertTimingAlmostEqual(join.elapsed, 0.0)
540 self.assertEqual(p.is_alive(), True)
541
542 self.assertEqual(join(-1), None)
543 self.assertTimingAlmostEqual(join.elapsed, 0.0)
544 self.assertEqual(p.is_alive(), True)
545
546 timeout = support.SHORT_TIMEOUT
547 if not event.wait(timeout):
548 p.terminate()
549 p.join()
550 self.fail(f"event not signaled in {timeout} seconds")
551
552 meth(p)
553
554 if hasattr(signal, 'alarm'):
555 # On the Gentoo buildbot waitpid() often seems to block forever.
556 # We use alarm() to interrupt it if it blocks for too long.
557 def handler(*args):
558 raise RuntimeError('join took too long: %s' % p)
559 old_handler = signal.signal(signal.SIGALRM, handler)
560 try:
561 signal.alarm(10)
562 self.assertEqual(join(), None)
563 finally:
564 signal.alarm(0)
565 signal.signal(signal.SIGALRM, old_handler)
566 else:
567 self.assertEqual(join(), None)
568
569 self.assertTimingAlmostEqual(join.elapsed, 0.0)
570
571 self.assertEqual(p.is_alive(), False)
572 self.assertNotIn(p, self.active_children())
573
574 p.join()
575
576 return p.exitcode
577
578 def test_terminate(self):
579 exitcode = self._kill_process(multiprocessing.Process.terminate)
580 self.assertEqual(exitcode, -signal.SIGTERM)
581
582 def test_kill(self):
583 exitcode = self._kill_process(multiprocessing.Process.kill)
584 if os.name != 'nt':
585 self.assertEqual(exitcode, -signal.SIGKILL)
586 else:
587 self.assertEqual(exitcode, -signal.SIGTERM)
588
589 def test_cpu_count(self):
590 try:
591 cpus = multiprocessing.cpu_count()
592 except NotImplementedError:
593 cpus = 1
594 self.assertTrue(type(cpus) is int)
595 self.assertTrue(cpus >= 1)
596
597 def test_active_children(self):
598 self.assertEqual(type(self.active_children()), list)
599
600 event = self.Event()
601 p = self.Process(target=event.wait, args=())
602 self.assertNotIn(p, self.active_children())
603
604 try:
605 p.daemon = True
606 p.start()
607 self.assertIn(p, self.active_children())
608 finally:
609 event.set()
610
611 p.join()
612 self.assertNotIn(p, self.active_children())
613
614 @classmethod
615 def _test_recursion(cls, wconn, id):
616 wconn.send(id)
617 if len(id) < 2:
618 for i in range(2):
619 p = cls.Process(
620 target=cls._test_recursion, args=(wconn, id+[i])
621 )
622 p.start()
623 p.join()
624
625 def test_recursion(self):
626 rconn, wconn = self.Pipe(duplex=False)
627 self._test_recursion(wconn, [])
628
629 time.sleep(DELTA)
630 result = []
631 while rconn.poll():
632 result.append(rconn.recv())
633
634 expected = [
635 [],
636 [0],
637 [0, 0],
638 [0, 1],
639 [1],
640 [1, 0],
641 [1, 1]
642 ]
643 self.assertEqual(result, expected)
644
645 @classmethod
646 def _test_sentinel(cls, event):
647 event.wait(10.0)
648
649 def test_sentinel(self):
650 if self.TYPE == "threads":
651 self.skipTest('test not appropriate for {}'.format(self.TYPE))
652 event = self.Event()
653 p = self.Process(target=self._test_sentinel, args=(event,))
654 with self.assertRaises(ValueError):
655 p.sentinel
656 p.start()
657 self.addCleanup(p.join)
658 sentinel = p.sentinel
659 self.assertIsInstance(sentinel, int)
660 self.assertFalse(wait_for_handle(sentinel, timeout=0.0))
661 event.set()
662 p.join()
663 self.assertTrue(wait_for_handle(sentinel, timeout=1))
664
665 @classmethod
666 def _test_close(cls, rc=0, q=None):
667 if q is not None:
668 q.get()
669 sys.exit(rc)
670
671 def test_close(self):
672 if self.TYPE == "threads":
673 self.skipTest('test not appropriate for {}'.format(self.TYPE))
674 q = self.Queue()
675 p = self.Process(target=self._test_close, kwargs={'q': q})
676 p.daemon = True
677 p.start()
678 self.assertEqual(p.is_alive(), True)
679 # Child is still alive, cannot close
680 with self.assertRaises(ValueError):
681 p.close()
682
683 q.put(None)
684 p.join()
685 self.assertEqual(p.is_alive(), False)
686 self.assertEqual(p.exitcode, 0)
687 p.close()
688 with self.assertRaises(ValueError):
689 p.is_alive()
690 with self.assertRaises(ValueError):
691 p.join()
692 with self.assertRaises(ValueError):
693 p.terminate()
694 p.close()
695
696 wr = weakref.ref(p)
697 del p
698 gc.collect()
699 self.assertIs(wr(), None)
700
701 close_queue(q)
702
703 @support.requires_resource('walltime')
704 def test_many_processes(self):
705 if self.TYPE == 'threads':
706 self.skipTest('test not appropriate for {}'.format(self.TYPE))
707
708 sm = multiprocessing.get_start_method()
709 N = 5 if sm == 'spawn' else 100
710
711 # Try to overwhelm the forkserver loop with events
712 procs = [self.Process(target=self._test_sleep, args=(0.01,))
713 for i in range(N)]
714 for p in procs:
715 p.start()
716 for p in procs:
717 join_process(p)
718 for p in procs:
719 self.assertEqual(p.exitcode, 0)
720
721 procs = [self.Process(target=self._sleep_some)
722 for i in range(N)]
723 for p in procs:
724 p.start()
725 time.sleep(0.001) # let the children start...
726 for p in procs:
727 p.terminate()
728 for p in procs:
729 join_process(p)
730 if os.name != 'nt':
731 exitcodes = [-signal.SIGTERM]
732 if sys.platform == 'darwin':
733 # bpo-31510: On macOS, killing a freshly started process with
734 # SIGTERM sometimes kills the process with SIGKILL.
735 exitcodes.append(-signal.SIGKILL)
736 for p in procs:
737 self.assertIn(p.exitcode, exitcodes)
738
739 def test_lose_target_ref(self):
740 c = DummyCallable()
741 wr = weakref.ref(c)
742 q = self.Queue()
743 p = self.Process(target=c, args=(q, c))
744 del c
745 p.start()
746 p.join()
747 gc.collect() # For PyPy or other GCs.
748 self.assertIs(wr(), None)
749 self.assertEqual(q.get(), 5)
750 close_queue(q)
751
752 @classmethod
753 def _test_child_fd_inflation(self, evt, q):
754 q.put(os_helper.fd_count())
755 evt.wait()
756
757 def test_child_fd_inflation(self):
758 # Number of fds in child processes should not grow with the
759 # number of running children.
760 if self.TYPE == 'threads':
761 self.skipTest('test not appropriate for {}'.format(self.TYPE))
762
763 sm = multiprocessing.get_start_method()
764 if sm == 'fork':
765 # The fork method by design inherits all fds from the parent,
766 # trying to go against it is a lost battle
767 self.skipTest('test not appropriate for {}'.format(sm))
768
769 N = 5
770 evt = self.Event()
771 q = self.Queue()
772
773 procs = [self.Process(target=self._test_child_fd_inflation, args=(evt, q))
774 for i in range(N)]
775 for p in procs:
776 p.start()
777
778 try:
779 fd_counts = [q.get() for i in range(N)]
780 self.assertEqual(len(set(fd_counts)), 1, fd_counts)
781
782 finally:
783 evt.set()
784 for p in procs:
785 p.join()
786 close_queue(q)
787
788 @classmethod
789 def _test_wait_for_threads(self, evt):
790 def func1():
791 time.sleep(0.5)
792 evt.set()
793
794 def func2():
795 time.sleep(20)
796 evt.clear()
797
798 threading.Thread(target=func1).start()
799 threading.Thread(target=func2, daemon=True).start()
800
801 def test_wait_for_threads(self):
802 # A child process should wait for non-daemonic threads to end
803 # before exiting
804 if self.TYPE == 'threads':
805 self.skipTest('test not appropriate for {}'.format(self.TYPE))
806
807 evt = self.Event()
808 proc = self.Process(target=self._test_wait_for_threads, args=(evt,))
809 proc.start()
810 proc.join()
811 self.assertTrue(evt.is_set())
812
813 @classmethod
814 def _test_error_on_stdio_flush(self, evt, break_std_streams={}):
815 for stream_name, action in break_std_streams.items():
816 if action == 'close':
817 stream = io.StringIO()
818 stream.close()
819 else:
820 assert action == 'remove'
821 stream = None
822 setattr(sys, stream_name, None)
823 evt.set()
824
825 def test_error_on_stdio_flush_1(self):
826 # Check that Process works with broken standard streams
827 streams = [io.StringIO(), None]
828 streams[0].close()
829 for stream_name in ('stdout', 'stderr'):
830 for stream in streams:
831 old_stream = getattr(sys, stream_name)
832 setattr(sys, stream_name, stream)
833 try:
834 evt = self.Event()
835 proc = self.Process(target=self._test_error_on_stdio_flush,
836 args=(evt,))
837 proc.start()
838 proc.join()
839 self.assertTrue(evt.is_set())
840 self.assertEqual(proc.exitcode, 0)
841 finally:
842 setattr(sys, stream_name, old_stream)
843
844 def test_error_on_stdio_flush_2(self):
845 # Same as test_error_on_stdio_flush_1(), but standard streams are
846 # broken by the child process
847 for stream_name in ('stdout', 'stderr'):
848 for action in ('close', 'remove'):
849 old_stream = getattr(sys, stream_name)
850 try:
851 evt = self.Event()
852 proc = self.Process(target=self._test_error_on_stdio_flush,
853 args=(evt, {stream_name: action}))
854 proc.start()
855 proc.join()
856 self.assertTrue(evt.is_set())
857 self.assertEqual(proc.exitcode, 0)
858 finally:
859 setattr(sys, stream_name, old_stream)
860
861 @classmethod
862 def _sleep_and_set_event(self, evt, delay=0.0):
863 time.sleep(delay)
864 evt.set()
865
866 def check_forkserver_death(self, signum):
867 # bpo-31308: if the forkserver process has died, we should still
868 # be able to create and run new Process instances (the forkserver
869 # is implicitly restarted).
870 if self.TYPE == 'threads':
871 self.skipTest('test not appropriate for {}'.format(self.TYPE))
872 sm = multiprocessing.get_start_method()
873 if sm != 'forkserver':
874 # The fork method by design inherits all fds from the parent,
875 # trying to go against it is a lost battle
876 self.skipTest('test not appropriate for {}'.format(sm))
877
878 from multiprocessing.forkserver import _forkserver
879 _forkserver.ensure_running()
880
881 # First process sleeps 500 ms
882 delay = 0.5
883
884 evt = self.Event()
885 proc = self.Process(target=self._sleep_and_set_event, args=(evt, delay))
886 proc.start()
887
888 pid = _forkserver._forkserver_pid
889 os.kill(pid, signum)
890 # give time to the fork server to die and time to proc to complete
891 time.sleep(delay * 2.0)
892
893 evt2 = self.Event()
894 proc2 = self.Process(target=self._sleep_and_set_event, args=(evt2,))
895 proc2.start()
896 proc2.join()
897 self.assertTrue(evt2.is_set())
898 self.assertEqual(proc2.exitcode, 0)
899
900 proc.join()
901 self.assertTrue(evt.is_set())
902 self.assertIn(proc.exitcode, (0, 255))
903
904 def test_forkserver_sigint(self):
905 # Catchable signal
906 self.check_forkserver_death(signal.SIGINT)
907
908 def test_forkserver_sigkill(self):
909 # Uncatchable signal
910 if os.name != 'nt':
911 self.check_forkserver_death(signal.SIGKILL)
912
913
914 #
915 #
916 #
917
918 class _UpperCaser(multiprocessing.Process):
919
920 def __init__(self):
921 multiprocessing.Process.__init__(self)
922 self.child_conn, self.parent_conn = multiprocessing.Pipe()
923
924 def run(self):
925 self.parent_conn.close()
926 for s in iter(self.child_conn.recv, None):
927 self.child_conn.send(s.upper())
928 self.child_conn.close()
929
930 def submit(self, s):
931 assert type(s) is str
932 self.parent_conn.send(s)
933 return self.parent_conn.recv()
934
935 def stop(self):
936 self.parent_conn.send(None)
937 self.parent_conn.close()
938 self.child_conn.close()
939
940 class _TestSubclassingProcess(BaseTestCase):
941
942 ALLOWED_TYPES = ('processes',)
943
944 def test_subclassing(self):
945 uppercaser = _UpperCaser()
946 uppercaser.daemon = True
947 uppercaser.start()
948 self.assertEqual(uppercaser.submit('hello'), 'HELLO')
949 self.assertEqual(uppercaser.submit('world'), 'WORLD')
950 uppercaser.stop()
951 uppercaser.join()
952
953 def test_stderr_flush(self):
954 # sys.stderr is flushed at process shutdown (issue #13812)
955 if self.TYPE == "threads":
956 self.skipTest('test not appropriate for {}'.format(self.TYPE))
957
958 testfn = os_helper.TESTFN
959 self.addCleanup(os_helper.unlink, testfn)
960 proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
961 proc.start()
962 proc.join()
963 with open(testfn, encoding="utf-8") as f:
964 err = f.read()
965 # The whole traceback was printed
966 self.assertIn("ZeroDivisionError", err)
967 self.assertIn("test_multiprocessing.py", err)
968 self.assertIn("1/0 # MARKER", err)
969
970 @classmethod
971 def _test_stderr_flush(cls, testfn):
972 fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
973 sys.stderr = open(fd, 'w', encoding="utf-8", closefd=False)
974 1/0 # MARKER
975
976
977 @classmethod
978 def _test_sys_exit(cls, reason, testfn):
979 fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
980 sys.stderr = open(fd, 'w', encoding="utf-8", closefd=False)
981 sys.exit(reason)
982
983 def test_sys_exit(self):
984 # See Issue 13854
985 if self.TYPE == 'threads':
986 self.skipTest('test not appropriate for {}'.format(self.TYPE))
987
988 testfn = os_helper.TESTFN
989 self.addCleanup(os_helper.unlink, testfn)
990
991 for reason in (
992 [1, 2, 3],
993 'ignore this',
994 ):
995 p = self.Process(target=self._test_sys_exit, args=(reason, testfn))
996 p.daemon = True
997 p.start()
998 join_process(p)
999 self.assertEqual(p.exitcode, 1)
1000
1001 with open(testfn, encoding="utf-8") as f:
1002 content = f.read()
1003 self.assertEqual(content.rstrip(), str(reason))
1004
1005 os.unlink(testfn)
1006
1007 cases = [
1008 ((True,), 1),
1009 ((False,), 0),
1010 ((8,), 8),
1011 ((None,), 0),
1012 ((), 0),
1013 ]
1014
1015 for args, expected in cases:
1016 with self.subTest(args=args):
1017 p = self.Process(target=sys.exit, args=args)
1018 p.daemon = True
1019 p.start()
1020 join_process(p)
1021 self.assertEqual(p.exitcode, expected)
1022
1023 #
1024 #
1025 #
1026
1027 def queue_empty(q):
1028 if hasattr(q, 'empty'):
1029 return q.empty()
1030 else:
1031 return q.qsize() == 0
1032
1033 def queue_full(q, maxsize):
1034 if hasattr(q, 'full'):
1035 return q.full()
1036 else:
1037 return q.qsize() == maxsize
1038
1039
1040 class _TestQueue(BaseTestCase):
1041
1042
1043 @classmethod
1044 def _test_put(cls, queue, child_can_start, parent_can_continue):
1045 child_can_start.wait()
1046 for i in range(6):
1047 queue.get()
1048 parent_can_continue.set()
1049
1050 def test_put(self):
1051 MAXSIZE = 6
1052 queue = self.Queue(maxsize=MAXSIZE)
1053 child_can_start = self.Event()
1054 parent_can_continue = self.Event()
1055
1056 proc = self.Process(
1057 target=self._test_put,
1058 args=(queue, child_can_start, parent_can_continue)
1059 )
1060 proc.daemon = True
1061 proc.start()
1062
1063 self.assertEqual(queue_empty(queue), True)
1064 self.assertEqual(queue_full(queue, MAXSIZE), False)
1065
1066 queue.put(1)
1067 queue.put(2, True)
1068 queue.put(3, True, None)
1069 queue.put(4, False)
1070 queue.put(5, False, None)
1071 queue.put_nowait(6)
1072
1073 # the values may be in buffer but not yet in pipe so sleep a bit
1074 time.sleep(DELTA)
1075
1076 self.assertEqual(queue_empty(queue), False)
1077 self.assertEqual(queue_full(queue, MAXSIZE), True)
1078
1079 put = TimingWrapper(queue.put)
1080 put_nowait = TimingWrapper(queue.put_nowait)
1081
1082 self.assertRaises(pyqueue.Full, put, 7, False)
1083 self.assertTimingAlmostEqual(put.elapsed, 0)
1084
1085 self.assertRaises(pyqueue.Full, put, 7, False, None)
1086 self.assertTimingAlmostEqual(put.elapsed, 0)
1087
1088 self.assertRaises(pyqueue.Full, put_nowait, 7)
1089 self.assertTimingAlmostEqual(put_nowait.elapsed, 0)
1090
1091 self.assertRaises(pyqueue.Full, put, 7, True, TIMEOUT1)
1092 self.assertTimingAlmostEqual(put.elapsed, TIMEOUT1)
1093
1094 self.assertRaises(pyqueue.Full, put, 7, False, TIMEOUT2)
1095 self.assertTimingAlmostEqual(put.elapsed, 0)
1096
1097 self.assertRaises(pyqueue.Full, put, 7, True, timeout=TIMEOUT3)
1098 self.assertTimingAlmostEqual(put.elapsed, TIMEOUT3)
1099
1100 child_can_start.set()
1101 parent_can_continue.wait()
1102
1103 self.assertEqual(queue_empty(queue), True)
1104 self.assertEqual(queue_full(queue, MAXSIZE), False)
1105
1106 proc.join()
1107 close_queue(queue)
1108
1109 @classmethod
1110 def _test_get(cls, queue, child_can_start, parent_can_continue):
1111 child_can_start.wait()
1112 queue.put(1)
1113 queue.put(2)
1114 queue.put(3)
1115 queue.put(4)
1116 queue.put(5)
1117 parent_can_continue.set()
1118
1119 def test_get(self):
1120 queue = self.Queue()
1121 child_can_start = self.Event()
1122 parent_can_continue = self.Event()
1123
1124 proc = self.Process(
1125 target=self._test_get,
1126 args=(queue, child_can_start, parent_can_continue)
1127 )
1128 proc.daemon = True
1129 proc.start()
1130
1131 self.assertEqual(queue_empty(queue), True)
1132
1133 child_can_start.set()
1134 parent_can_continue.wait()
1135
1136 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
1137 if not queue_empty(queue):
1138 break
1139 self.assertEqual(queue_empty(queue), False)
1140
1141 self.assertEqual(queue.get_nowait(), 1)
1142 self.assertEqual(queue.get(True, None), 2)
1143 self.assertEqual(queue.get(True), 3)
1144 self.assertEqual(queue.get(timeout=1), 4)
1145 self.assertEqual(queue.get(), 5)
1146
1147 self.assertEqual(queue_empty(queue), True)
1148
1149 get = TimingWrapper(queue.get)
1150 get_nowait = TimingWrapper(queue.get_nowait)
1151
1152 self.assertRaises(pyqueue.Empty, get, False)
1153 self.assertTimingAlmostEqual(get.elapsed, 0)
1154
1155 self.assertRaises(pyqueue.Empty, get, False, None)
1156 self.assertTimingAlmostEqual(get.elapsed, 0)
1157
1158 self.assertRaises(pyqueue.Empty, get_nowait)
1159 self.assertTimingAlmostEqual(get_nowait.elapsed, 0)
1160
1161 self.assertRaises(pyqueue.Empty, get, True, TIMEOUT1)
1162 self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
1163
1164 self.assertRaises(pyqueue.Empty, get, False, TIMEOUT2)
1165 self.assertTimingAlmostEqual(get.elapsed, 0)
1166
1167 self.assertRaises(pyqueue.Empty, get, timeout=TIMEOUT3)
1168 self.assertTimingAlmostEqual(get.elapsed, TIMEOUT3)
1169
1170 proc.join()
1171 close_queue(queue)
1172
1173 @classmethod
1174 def _test_fork(cls, queue):
1175 for i in range(10, 20):
1176 queue.put(i)
1177 # note that at this point the items may only be buffered, so the
1178 # process cannot shutdown until the feeder thread has finished
1179 # pushing items onto the pipe.
1180
1181 def test_fork(self):
1182 # Old versions of Queue would fail to create a new feeder
1183 # thread for a forked process if the original process had its
1184 # own feeder thread. This test checks that this no longer
1185 # happens.
1186
1187 queue = self.Queue()
1188
1189 # put items on queue so that main process starts a feeder thread
1190 for i in range(10):
1191 queue.put(i)
1192
1193 # wait to make sure thread starts before we fork a new process
1194 time.sleep(DELTA)
1195
1196 # fork process
1197 p = self.Process(target=self._test_fork, args=(queue,))
1198 p.daemon = True
1199 p.start()
1200
1201 # check that all expected items are in the queue
1202 for i in range(20):
1203 self.assertEqual(queue.get(), i)
1204 self.assertRaises(pyqueue.Empty, queue.get, False)
1205
1206 p.join()
1207 close_queue(queue)
1208
1209 def test_qsize(self):
1210 q = self.Queue()
1211 try:
1212 self.assertEqual(q.qsize(), 0)
1213 except NotImplementedError:
1214 self.skipTest('qsize method not implemented')
1215 q.put(1)
1216 self.assertEqual(q.qsize(), 1)
1217 q.put(5)
1218 self.assertEqual(q.qsize(), 2)
1219 q.get()
1220 self.assertEqual(q.qsize(), 1)
1221 q.get()
1222 self.assertEqual(q.qsize(), 0)
1223 close_queue(q)
1224
1225 @classmethod
1226 def _test_task_done(cls, q):
1227 for obj in iter(q.get, None):
1228 time.sleep(DELTA)
1229 q.task_done()
1230
1231 def test_task_done(self):
1232 queue = self.JoinableQueue()
1233
1234 workers = [self.Process(target=self._test_task_done, args=(queue,))
1235 for i in range(4)]
1236
1237 for p in workers:
1238 p.daemon = True
1239 p.start()
1240
1241 for i in range(10):
1242 queue.put(i)
1243
1244 queue.join()
1245
1246 for p in workers:
1247 queue.put(None)
1248
1249 for p in workers:
1250 p.join()
1251 close_queue(queue)
1252
1253 def test_no_import_lock_contention(self):
1254 with os_helper.temp_cwd():
1255 module_name = 'imported_by_an_imported_module'
1256 with open(module_name + '.py', 'w', encoding="utf-8") as f:
1257 f.write("""if 1:
1258 import multiprocessing
1259
1260 q = multiprocessing.Queue()
1261 q.put('knock knock')
1262 q.get(timeout=3)
1263 q.close()
1264 del q
1265 """)
1266
1267 with import_helper.DirsOnSysPath(os.getcwd()):
1268 try:
1269 __import__(module_name)
1270 except pyqueue.Empty:
1271 self.fail("Probable regression on import lock contention;"
1272 " see Issue #22853")
1273
1274 def test_timeout(self):
1275 q = multiprocessing.Queue()
1276 start = time.monotonic()
1277 self.assertRaises(pyqueue.Empty, q.get, True, 0.200)
1278 delta = time.monotonic() - start
1279 # bpo-30317: Tolerate a delta of 100 ms because of the bad clock
1280 # resolution on Windows (usually 15.6 ms). x86 Windows7 3.x once
1281 # failed because the delta was only 135.8 ms.
1282 self.assertGreaterEqual(delta, 0.100)
1283 close_queue(q)
1284
1285 def test_queue_feeder_donot_stop_onexc(self):
1286 # bpo-30414: verify feeder handles exceptions correctly
1287 if self.TYPE != 'processes':
1288 self.skipTest('test not appropriate for {}'.format(self.TYPE))
1289
1290 class NotSerializable(object):
1291 def __reduce__(self):
1292 raise AttributeError
1293 with test.support.captured_stderr():
1294 q = self.Queue()
1295 q.put(NotSerializable())
1296 q.put(True)
1297 self.assertTrue(q.get(timeout=support.SHORT_TIMEOUT))
1298 close_queue(q)
1299
1300 with test.support.captured_stderr():
1301 # bpo-33078: verify that the queue size is correctly handled
1302 # on errors.
1303 q = self.Queue(maxsize=1)
1304 q.put(NotSerializable())
1305 q.put(True)
1306 try:
1307 self.assertEqual(q.qsize(), 1)
1308 except NotImplementedError:
1309 # qsize is not available on all platform as it
1310 # relies on sem_getvalue
1311 pass
1312 self.assertTrue(q.get(timeout=support.SHORT_TIMEOUT))
1313 # Check that the size of the queue is correct
1314 self.assertTrue(q.empty())
1315 close_queue(q)
1316
1317 def test_queue_feeder_on_queue_feeder_error(self):
1318 # bpo-30006: verify feeder handles exceptions using the
1319 # _on_queue_feeder_error hook.
1320 if self.TYPE != 'processes':
1321 self.skipTest('test not appropriate for {}'.format(self.TYPE))
1322
1323 class NotSerializable(object):
1324 """Mock unserializable object"""
1325 def __init__(self):
1326 self.reduce_was_called = False
1327 self.on_queue_feeder_error_was_called = False
1328
1329 def __reduce__(self):
1330 self.reduce_was_called = True
1331 raise AttributeError
1332
1333 class SafeQueue(multiprocessing.queues.Queue):
1334 """Queue with overloaded _on_queue_feeder_error hook"""
1335 @staticmethod
1336 def _on_queue_feeder_error(e, obj):
1337 if (isinstance(e, AttributeError) and
1338 isinstance(obj, NotSerializable)):
1339 obj.on_queue_feeder_error_was_called = True
1340
1341 not_serializable_obj = NotSerializable()
1342 # The captured_stderr reduces the noise in the test report
1343 with test.support.captured_stderr():
1344 q = SafeQueue(ctx=multiprocessing.get_context())
1345 q.put(not_serializable_obj)
1346
1347 # Verify that q is still functioning correctly
1348 q.put(True)
1349 self.assertTrue(q.get(timeout=support.SHORT_TIMEOUT))
1350
1351 # Assert that the serialization and the hook have been called correctly
1352 self.assertTrue(not_serializable_obj.reduce_was_called)
1353 self.assertTrue(not_serializable_obj.on_queue_feeder_error_was_called)
1354
1355 def test_closed_queue_empty_exceptions(self):
1356 # Assert that checking the emptiness of an unused closed queue
1357 # does not raise an OSError. The rationale is that q.close() is
1358 # a no-op upon construction and becomes effective once the queue
1359 # has been used (e.g., by calling q.put()).
1360 for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
1361 q.close() # this is a no-op since the feeder thread is None
1362 q.join_thread() # this is also a no-op
1363 self.assertTrue(q.empty())
1364
1365 for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
1366 q.put('foo') # make sure that the queue is 'used'
1367 q.close() # close the feeder thread
1368 q.join_thread() # make sure to join the feeder thread
1369 with self.assertRaisesRegex(OSError, 'is closed'):
1370 q.empty()
1371
1372 def test_closed_queue_put_get_exceptions(self):
1373 for q in multiprocessing.Queue(), multiprocessing.JoinableQueue():
1374 q.close()
1375 with self.assertRaisesRegex(ValueError, 'is closed'):
1376 q.put('foo')
1377 with self.assertRaisesRegex(ValueError, 'is closed'):
1378 q.get()
1379 #
1380 #
1381 #
1382
1383 class _TestLock(BaseTestCase):
1384
1385 @staticmethod
1386 def _acquire(lock, l=None):
1387 lock.acquire()
1388 if l is not None:
1389 l.append(repr(lock))
1390
1391 @staticmethod
1392 def _acquire_event(lock, event):
1393 lock.acquire()
1394 event.set()
1395 time.sleep(1.0)
1396
1397 def test_repr_lock(self):
1398 if self.TYPE != 'processes':
1399 self.skipTest('test not appropriate for {}'.format(self.TYPE))
1400
1401 lock = self.Lock()
1402 self.assertEqual(f'<Lock(owner=None)>', repr(lock))
1403
1404 lock.acquire()
1405 self.assertEqual(f'<Lock(owner=MainProcess)>', repr(lock))
1406 lock.release()
1407
1408 tname = 'T1'
1409 l = []
1410 t = threading.Thread(target=self._acquire,
1411 args=(lock, l),
1412 name=tname)
1413 t.start()
1414 time.sleep(0.1)
1415 self.assertEqual(f'<Lock(owner=MainProcess|{tname})>', l[0])
1416 lock.release()
1417
1418 t = threading.Thread(target=self._acquire,
1419 args=(lock,),
1420 name=tname)
1421 t.start()
1422 time.sleep(0.1)
1423 self.assertEqual('<Lock(owner=SomeOtherThread)>', repr(lock))
1424 lock.release()
1425
1426 pname = 'P1'
1427 l = multiprocessing.Manager().list()
1428 p = self.Process(target=self._acquire,
1429 args=(lock, l),
1430 name=pname)
1431 p.start()
1432 p.join()
1433 self.assertEqual(f'<Lock(owner={pname})>', l[0])
1434
1435 lock = self.Lock()
1436 event = self.Event()
1437 p = self.Process(target=self._acquire_event,
1438 args=(lock, event),
1439 name='P2')
1440 p.start()
1441 event.wait()
1442 self.assertEqual(f'<Lock(owner=SomeOtherProcess)>', repr(lock))
1443 p.terminate()
1444
1445 def test_lock(self):
1446 lock = self.Lock()
1447 self.assertEqual(lock.acquire(), True)
1448 self.assertEqual(lock.acquire(False), False)
1449 self.assertEqual(lock.release(), None)
1450 self.assertRaises((ValueError, threading.ThreadError), lock.release)
1451
1452 @staticmethod
1453 def _acquire_release(lock, timeout, l=None, n=1):
1454 for _ in range(n):
1455 lock.acquire()
1456 if l is not None:
1457 l.append(repr(lock))
1458 time.sleep(timeout)
1459 for _ in range(n):
1460 lock.release()
1461
1462 def test_repr_rlock(self):
1463 if self.TYPE != 'processes':
1464 self.skipTest('test not appropriate for {}'.format(self.TYPE))
1465
1466 lock = self.RLock()
1467 self.assertEqual('<RLock(None, 0)>', repr(lock))
1468
1469 n = 3
1470 for _ in range(n):
1471 lock.acquire()
1472 self.assertEqual(f'<RLock(MainProcess, {n})>', repr(lock))
1473 for _ in range(n):
1474 lock.release()
1475
1476 t, l = [], []
1477 for i in range(n):
1478 t.append(threading.Thread(target=self._acquire_release,
1479 args=(lock, 0.1, l, i+1),
1480 name=f'T{i+1}'))
1481 t[-1].start()
1482 for t_ in t:
1483 t_.join()
1484 for i in range(n):
1485 self.assertIn(f'<RLock(MainProcess|T{i+1}, {i+1})>', l)
1486
1487 rlock = self.RLock()
1488 t = threading.Thread(target=rlock.acquire)
1489 t.start()
1490 t.join()
1491 self.assertEqual('<RLock(SomeOtherThread, nonzero)>', repr(rlock))
1492
1493 pname = 'P1'
1494 l = multiprocessing.Manager().list()
1495 p = self.Process(target=self._acquire_release,
1496 args=(lock, 0.1, l),
1497 name=pname)
1498 p.start()
1499 p.join()
1500 self.assertEqual(f'<RLock({pname}, 1)>', l[0])
1501
1502 rlock = self.RLock()
1503 p = self.Process(target=self._acquire, args=(rlock,))
1504 p.start()
1505 p.join()
1506 self.assertEqual('<RLock(SomeOtherProcess, nonzero)>', repr(rlock))
1507
1508 def test_rlock(self):
1509 lock = self.RLock()
1510 self.assertEqual(lock.acquire(), True)
1511 self.assertEqual(lock.acquire(), True)
1512 self.assertEqual(lock.acquire(), True)
1513 self.assertEqual(lock.release(), None)
1514 self.assertEqual(lock.release(), None)
1515 self.assertEqual(lock.release(), None)
1516 self.assertRaises((AssertionError, RuntimeError), lock.release)
1517
1518 def test_lock_context(self):
1519 with self.Lock():
1520 pass
1521
1522
1523 class _TestSemaphore(BaseTestCase):
1524
1525 def _test_semaphore(self, sem):
1526 self.assertReturnsIfImplemented(2, get_value, sem)
1527 self.assertEqual(sem.acquire(), True)
1528 self.assertReturnsIfImplemented(1, get_value, sem)
1529 self.assertEqual(sem.acquire(), True)
1530 self.assertReturnsIfImplemented(0, get_value, sem)
1531 self.assertEqual(sem.acquire(False), False)
1532 self.assertReturnsIfImplemented(0, get_value, sem)
1533 self.assertEqual(sem.release(), None)
1534 self.assertReturnsIfImplemented(1, get_value, sem)
1535 self.assertEqual(sem.release(), None)
1536 self.assertReturnsIfImplemented(2, get_value, sem)
1537
1538 def test_semaphore(self):
1539 sem = self.Semaphore(2)
1540 self._test_semaphore(sem)
1541 self.assertEqual(sem.release(), None)
1542 self.assertReturnsIfImplemented(3, get_value, sem)
1543 self.assertEqual(sem.release(), None)
1544 self.assertReturnsIfImplemented(4, get_value, sem)
1545
1546 def test_bounded_semaphore(self):
1547 sem = self.BoundedSemaphore(2)
1548 self._test_semaphore(sem)
1549 # Currently fails on OS/X
1550 #if HAVE_GETVALUE:
1551 # self.assertRaises(ValueError, sem.release)
1552 # self.assertReturnsIfImplemented(2, get_value, sem)
1553
1554 def test_timeout(self):
1555 if self.TYPE != 'processes':
1556 self.skipTest('test not appropriate for {}'.format(self.TYPE))
1557
1558 sem = self.Semaphore(0)
1559 acquire = TimingWrapper(sem.acquire)
1560
1561 self.assertEqual(acquire(False), False)
1562 self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
1563
1564 self.assertEqual(acquire(False, None), False)
1565 self.assertTimingAlmostEqual(acquire.elapsed, 0.0)
1566
1567 self.assertEqual(acquire(False, TIMEOUT1), False)
1568 self.assertTimingAlmostEqual(acquire.elapsed, 0)
1569
1570 self.assertEqual(acquire(True, TIMEOUT2), False)
1571 self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT2)
1572
1573 self.assertEqual(acquire(timeout=TIMEOUT3), False)
1574 self.assertTimingAlmostEqual(acquire.elapsed, TIMEOUT3)
1575
1576
1577 class _TestCondition(BaseTestCase):
1578
1579 @classmethod
1580 def f(cls, cond, sleeping, woken, timeout=None):
1581 cond.acquire()
1582 sleeping.release()
1583 cond.wait(timeout)
1584 woken.release()
1585 cond.release()
1586
1587 def assertReachesEventually(self, func, value):
1588 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
1589 try:
1590 if func() == value:
1591 break
1592 except NotImplementedError:
1593 break
1594
1595 self.assertReturnsIfImplemented(value, func)
1596
1597 def check_invariant(self, cond):
1598 # this is only supposed to succeed when there are no sleepers
1599 if self.TYPE == 'processes':
1600 try:
1601 sleepers = (cond._sleeping_count.get_value() -
1602 cond._woken_count.get_value())
1603 self.assertEqual(sleepers, 0)
1604 self.assertEqual(cond._wait_semaphore.get_value(), 0)
1605 except NotImplementedError:
1606 pass
1607
1608 def test_notify(self):
1609 cond = self.Condition()
1610 sleeping = self.Semaphore(0)
1611 woken = self.Semaphore(0)
1612
1613 p = self.Process(target=self.f, args=(cond, sleeping, woken))
1614 p.daemon = True
1615 p.start()
1616
1617 t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
1618 t.daemon = True
1619 t.start()
1620
1621 # wait for both children to start sleeping
1622 sleeping.acquire()
1623 sleeping.acquire()
1624
1625 # check no process/thread has woken up
1626 self.assertReachesEventually(lambda: get_value(woken), 0)
1627
1628 # wake up one process/thread
1629 cond.acquire()
1630 cond.notify()
1631 cond.release()
1632
1633 # check one process/thread has woken up
1634 self.assertReachesEventually(lambda: get_value(woken), 1)
1635
1636 # wake up another
1637 cond.acquire()
1638 cond.notify()
1639 cond.release()
1640
1641 # check other has woken up
1642 self.assertReachesEventually(lambda: get_value(woken), 2)
1643
1644 # check state is not mucked up
1645 self.check_invariant(cond)
1646
1647 threading_helper.join_thread(t)
1648 join_process(p)
1649
1650 def test_notify_all(self):
1651 cond = self.Condition()
1652 sleeping = self.Semaphore(0)
1653 woken = self.Semaphore(0)
1654
1655 # start some threads/processes which will timeout
1656 workers = []
1657 for i in range(3):
1658 p = self.Process(target=self.f,
1659 args=(cond, sleeping, woken, TIMEOUT1))
1660 p.daemon = True
1661 p.start()
1662 workers.append(p)
1663
1664 t = threading.Thread(target=self.f,
1665 args=(cond, sleeping, woken, TIMEOUT1))
1666 t.daemon = True
1667 t.start()
1668 workers.append(t)
1669
1670 # wait for them all to sleep
1671 for i in range(6):
1672 sleeping.acquire()
1673
1674 # check they have all timed out
1675 for i in range(6):
1676 woken.acquire()
1677 self.assertReturnsIfImplemented(0, get_value, woken)
1678
1679 # check state is not mucked up
1680 self.check_invariant(cond)
1681
1682 # start some more threads/processes
1683 for i in range(3):
1684 p = self.Process(target=self.f, args=(cond, sleeping, woken))
1685 p.daemon = True
1686 p.start()
1687 workers.append(p)
1688
1689 t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
1690 t.daemon = True
1691 t.start()
1692 workers.append(t)
1693
1694 # wait for them to all sleep
1695 for i in range(6):
1696 sleeping.acquire()
1697
1698 # check no process/thread has woken up
1699 time.sleep(DELTA)
1700 self.assertReturnsIfImplemented(0, get_value, woken)
1701
1702 # wake them all up
1703 cond.acquire()
1704 cond.notify_all()
1705 cond.release()
1706
1707 # check they have all woken
1708 for i in range(6):
1709 woken.acquire()
1710 self.assertReturnsIfImplemented(0, get_value, woken)
1711
1712 # check state is not mucked up
1713 self.check_invariant(cond)
1714
1715 for w in workers:
1716 # NOTE: join_process and join_thread are the same
1717 threading_helper.join_thread(w)
1718
1719 def test_notify_n(self):
1720 cond = self.Condition()
1721 sleeping = self.Semaphore(0)
1722 woken = self.Semaphore(0)
1723
1724 # start some threads/processes
1725 workers = []
1726 for i in range(3):
1727 p = self.Process(target=self.f, args=(cond, sleeping, woken))
1728 p.daemon = True
1729 p.start()
1730 workers.append(p)
1731
1732 t = threading.Thread(target=self.f, args=(cond, sleeping, woken))
1733 t.daemon = True
1734 t.start()
1735 workers.append(t)
1736
1737 # wait for them to all sleep
1738 for i in range(6):
1739 sleeping.acquire()
1740
1741 # check no process/thread has woken up
1742 time.sleep(DELTA)
1743 self.assertReturnsIfImplemented(0, get_value, woken)
1744
1745 # wake some of them up
1746 cond.acquire()
1747 cond.notify(n=2)
1748 cond.release()
1749
1750 # check 2 have woken
1751 self.assertReachesEventually(lambda: get_value(woken), 2)
1752
1753 # wake the rest of them
1754 cond.acquire()
1755 cond.notify(n=4)
1756 cond.release()
1757
1758 self.assertReachesEventually(lambda: get_value(woken), 6)
1759
1760 # doesn't do anything more
1761 cond.acquire()
1762 cond.notify(n=3)
1763 cond.release()
1764
1765 self.assertReturnsIfImplemented(6, get_value, woken)
1766
1767 # check state is not mucked up
1768 self.check_invariant(cond)
1769
1770 for w in workers:
1771 # NOTE: join_process and join_thread are the same
1772 threading_helper.join_thread(w)
1773
1774 def test_timeout(self):
1775 cond = self.Condition()
1776 wait = TimingWrapper(cond.wait)
1777 cond.acquire()
1778 res = wait(TIMEOUT1)
1779 cond.release()
1780 self.assertEqual(res, False)
1781 self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
1782
1783 @classmethod
1784 def _test_waitfor_f(cls, cond, state):
1785 with cond:
1786 state.value = 0
1787 cond.notify()
1788 result = cond.wait_for(lambda : state.value==4)
1789 if not result or state.value != 4:
1790 sys.exit(1)
1791
1792 @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
1793 def test_waitfor(self):
1794 # based on test in test/lock_tests.py
1795 cond = self.Condition()
1796 state = self.Value('i', -1)
1797
1798 p = self.Process(target=self._test_waitfor_f, args=(cond, state))
1799 p.daemon = True
1800 p.start()
1801
1802 with cond:
1803 result = cond.wait_for(lambda : state.value==0)
1804 self.assertTrue(result)
1805 self.assertEqual(state.value, 0)
1806
1807 for i in range(4):
1808 time.sleep(0.01)
1809 with cond:
1810 state.value += 1
1811 cond.notify()
1812
1813 join_process(p)
1814 self.assertEqual(p.exitcode, 0)
1815
1816 @classmethod
1817 def _test_waitfor_timeout_f(cls, cond, state, success, sem):
1818 sem.release()
1819 with cond:
1820 expected = 0.100
1821 dt = time.monotonic()
1822 result = cond.wait_for(lambda : state.value==4, timeout=expected)
1823 dt = time.monotonic() - dt
1824 if not result and (expected - CLOCK_RES) <= dt:
1825 success.value = True
1826
1827 @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes')
1828 def test_waitfor_timeout(self):
1829 # based on test in test/lock_tests.py
1830 cond = self.Condition()
1831 state = self.Value('i', 0)
1832 success = self.Value('i', False)
1833 sem = self.Semaphore(0)
1834
1835 p = self.Process(target=self._test_waitfor_timeout_f,
1836 args=(cond, state, success, sem))
1837 p.daemon = True
1838 p.start()
1839 self.assertTrue(sem.acquire(timeout=support.LONG_TIMEOUT))
1840
1841 # Only increment 3 times, so state == 4 is never reached.
1842 for i in range(3):
1843 time.sleep(0.010)
1844 with cond:
1845 state.value += 1
1846 cond.notify()
1847
1848 join_process(p)
1849 self.assertTrue(success.value)
1850
1851 @classmethod
1852 def _test_wait_result(cls, c, pid):
1853 with c:
1854 c.notify()
1855 time.sleep(1)
1856 if pid is not None:
1857 os.kill(pid, signal.SIGINT)
1858
1859 def test_wait_result(self):
1860 if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
1861 pid = os.getpid()
1862 else:
1863 pid = None
1864
1865 c = self.Condition()
1866 with c:
1867 self.assertFalse(c.wait(0))
1868 self.assertFalse(c.wait(0.1))
1869
1870 p = self.Process(target=self._test_wait_result, args=(c, pid))
1871 p.start()
1872
1873 self.assertTrue(c.wait(60))
1874 if pid is not None:
1875 self.assertRaises(KeyboardInterrupt, c.wait, 60)
1876
1877 p.join()
1878
1879
1880 class _TestEvent(BaseTestCase):
1881
1882 @classmethod
1883 def _test_event(cls, event):
1884 time.sleep(TIMEOUT2)
1885 event.set()
1886
1887 def test_event(self):
1888 event = self.Event()
1889 wait = TimingWrapper(event.wait)
1890
1891 # Removed temporarily, due to API shear, this does not
1892 # work with threading._Event objects. is_set == isSet
1893 self.assertEqual(event.is_set(), False)
1894
1895 # Removed, threading.Event.wait() will return the value of the __flag
1896 # instead of None. API Shear with the semaphore backed mp.Event
1897 self.assertEqual(wait(0.0), False)
1898 self.assertTimingAlmostEqual(wait.elapsed, 0.0)
1899 self.assertEqual(wait(TIMEOUT1), False)
1900 self.assertTimingAlmostEqual(wait.elapsed, TIMEOUT1)
1901
1902 event.set()
1903
1904 # See note above on the API differences
1905 self.assertEqual(event.is_set(), True)
1906 self.assertEqual(wait(), True)
1907 self.assertTimingAlmostEqual(wait.elapsed, 0.0)
1908 self.assertEqual(wait(TIMEOUT1), True)
1909 self.assertTimingAlmostEqual(wait.elapsed, 0.0)
1910 # self.assertEqual(event.is_set(), True)
1911
1912 event.clear()
1913
1914 #self.assertEqual(event.is_set(), False)
1915
1916 p = self.Process(target=self._test_event, args=(event,))
1917 p.daemon = True
1918 p.start()
1919 self.assertEqual(wait(), True)
1920 p.join()
1921
1922 def test_repr(self) -> None:
1923 event = self.Event()
1924 if self.TYPE == 'processes':
1925 self.assertRegex(repr(event), r"<Event at .* unset>")
1926 event.set()
1927 self.assertRegex(repr(event), r"<Event at .* set>")
1928 event.clear()
1929 self.assertRegex(repr(event), r"<Event at .* unset>")
1930 elif self.TYPE == 'manager':
1931 self.assertRegex(repr(event), r"<EventProxy object, typeid 'Event' at .*")
1932 event.set()
1933 self.assertRegex(repr(event), r"<EventProxy object, typeid 'Event' at .*")
1934
1935
1936 # Tests for Barrier - adapted from tests in test/lock_tests.py
1937 #
1938
1939 # Many of the tests for threading.Barrier use a list as an atomic
1940 # counter: a value is appended to increment the counter, and the
1941 # length of the list gives the value. We use the class DummyList
1942 # for the same purpose.
1943
1944 class _DummyList(object):
1945
1946 def __init__(self):
1947 wrapper = multiprocessing.heap.BufferWrapper(struct.calcsize('i'))
1948 lock = multiprocessing.Lock()
1949 self.__setstate__((wrapper, lock))
1950 self._lengthbuf[0] = 0
1951
1952 def __setstate__(self, state):
1953 (self._wrapper, self._lock) = state
1954 self._lengthbuf = self._wrapper.create_memoryview().cast('i')
1955
1956 def __getstate__(self):
1957 return (self._wrapper, self._lock)
1958
1959 def append(self, _):
1960 with self._lock:
1961 self._lengthbuf[0] += 1
1962
1963 def __len__(self):
1964 with self._lock:
1965 return self._lengthbuf[0]
1966
1967 def _wait():
1968 # A crude wait/yield function not relying on synchronization primitives.
1969 time.sleep(0.01)
1970
1971
1972 class Bunch(object):
1973 """
1974 A bunch of threads.
1975 """
1976 def __init__(self, namespace, f, args, n, wait_before_exit=False):
1977 """
1978 Construct a bunch of `n` threads running the same function `f`.
1979 If `wait_before_exit` is True, the threads won't terminate until
1980 do_finish() is called.
1981 """
1982 self.f = f
1983 self.args = args
1984 self.n = n
1985 self.started = namespace.DummyList()
1986 self.finished = namespace.DummyList()
1987 self._can_exit = namespace.Event()
1988 if not wait_before_exit:
1989 self._can_exit.set()
1990
1991 threads = []
1992 for i in range(n):
1993 p = namespace.Process(target=self.task)
1994 p.daemon = True
1995 p.start()
1996 threads.append(p)
1997
1998 def finalize(threads):
1999 for p in threads:
2000 p.join()
2001
2002 self._finalizer = weakref.finalize(self, finalize, threads)
2003
2004 def task(self):
2005 pid = os.getpid()
2006 self.started.append(pid)
2007 try:
2008 self.f(*self.args)
2009 finally:
2010 self.finished.append(pid)
2011 self._can_exit.wait(30)
2012 assert self._can_exit.is_set()
2013
2014 def wait_for_started(self):
2015 while len(self.started) < self.n:
2016 _wait()
2017
2018 def wait_for_finished(self):
2019 while len(self.finished) < self.n:
2020 _wait()
2021
2022 def do_finish(self):
2023 self._can_exit.set()
2024
2025 def close(self):
2026 self._finalizer()
2027
2028
2029 class AppendTrue(object):
2030 def __init__(self, obj):
2031 self.obj = obj
2032 def __call__(self):
2033 self.obj.append(True)
2034
2035
2036 class _TestBarrier(BaseTestCase):
2037 """
2038 Tests for Barrier objects.
2039 """
2040 N = 5
2041 defaultTimeout = 30.0 # XXX Slow Windows buildbots need generous timeout
2042
2043 def setUp(self):
2044 self.barrier = self.Barrier(self.N, timeout=self.defaultTimeout)
2045
2046 def tearDown(self):
2047 self.barrier.abort()
2048 self.barrier = None
2049
2050 def DummyList(self):
2051 if self.TYPE == 'threads':
2052 return []
2053 elif self.TYPE == 'manager':
2054 return self.manager.list()
2055 else:
2056 return _DummyList()
2057
2058 def run_threads(self, f, args):
2059 b = Bunch(self, f, args, self.N-1)
2060 try:
2061 f(*args)
2062 b.wait_for_finished()
2063 finally:
2064 b.close()
2065
2066 @classmethod
2067 def multipass(cls, barrier, results, n):
2068 m = barrier.parties
2069 assert m == cls.N
2070 for i in range(n):
2071 results[0].append(True)
2072 assert len(results[1]) == i * m
2073 barrier.wait()
2074 results[1].append(True)
2075 assert len(results[0]) == (i + 1) * m
2076 barrier.wait()
2077 try:
2078 assert barrier.n_waiting == 0
2079 except NotImplementedError:
2080 pass
2081 assert not barrier.broken
2082
2083 def test_barrier(self, passes=1):
2084 """
2085 Test that a barrier is passed in lockstep
2086 """
2087 results = [self.DummyList(), self.DummyList()]
2088 self.run_threads(self.multipass, (self.barrier, results, passes))
2089
2090 def test_barrier_10(self):
2091 """
2092 Test that a barrier works for 10 consecutive runs
2093 """
2094 return self.test_barrier(10)
2095
2096 @classmethod
2097 def _test_wait_return_f(cls, barrier, queue):
2098 res = barrier.wait()
2099 queue.put(res)
2100
2101 def test_wait_return(self):
2102 """
2103 test the return value from barrier.wait
2104 """
2105 queue = self.Queue()
2106 self.run_threads(self._test_wait_return_f, (self.barrier, queue))
2107 results = [queue.get() for i in range(self.N)]
2108 self.assertEqual(results.count(0), 1)
2109 close_queue(queue)
2110
2111 @classmethod
2112 def _test_action_f(cls, barrier, results):
2113 barrier.wait()
2114 if len(results) != 1:
2115 raise RuntimeError
2116
2117 def test_action(self):
2118 """
2119 Test the 'action' callback
2120 """
2121 results = self.DummyList()
2122 barrier = self.Barrier(self.N, action=AppendTrue(results))
2123 self.run_threads(self._test_action_f, (barrier, results))
2124 self.assertEqual(len(results), 1)
2125
2126 @classmethod
2127 def _test_abort_f(cls, barrier, results1, results2):
2128 try:
2129 i = barrier.wait()
2130 if i == cls.N//2:
2131 raise RuntimeError
2132 barrier.wait()
2133 results1.append(True)
2134 except threading.BrokenBarrierError:
2135 results2.append(True)
2136 except RuntimeError:
2137 barrier.abort()
2138
2139 def test_abort(self):
2140 """
2141 Test that an abort will put the barrier in a broken state
2142 """
2143 results1 = self.DummyList()
2144 results2 = self.DummyList()
2145 self.run_threads(self._test_abort_f,
2146 (self.barrier, results1, results2))
2147 self.assertEqual(len(results1), 0)
2148 self.assertEqual(len(results2), self.N-1)
2149 self.assertTrue(self.barrier.broken)
2150
2151 @classmethod
2152 def _test_reset_f(cls, barrier, results1, results2, results3):
2153 i = barrier.wait()
2154 if i == cls.N//2:
2155 # Wait until the other threads are all in the barrier.
2156 while barrier.n_waiting < cls.N-1:
2157 time.sleep(0.001)
2158 barrier.reset()
2159 else:
2160 try:
2161 barrier.wait()
2162 results1.append(True)
2163 except threading.BrokenBarrierError:
2164 results2.append(True)
2165 # Now, pass the barrier again
2166 barrier.wait()
2167 results3.append(True)
2168
2169 def test_reset(self):
2170 """
2171 Test that a 'reset' on a barrier frees the waiting threads
2172 """
2173 results1 = self.DummyList()
2174 results2 = self.DummyList()
2175 results3 = self.DummyList()
2176 self.run_threads(self._test_reset_f,
2177 (self.barrier, results1, results2, results3))
2178 self.assertEqual(len(results1), 0)
2179 self.assertEqual(len(results2), self.N-1)
2180 self.assertEqual(len(results3), self.N)
2181
2182 @classmethod
2183 def _test_abort_and_reset_f(cls, barrier, barrier2,
2184 results1, results2, results3):
2185 try:
2186 i = barrier.wait()
2187 if i == cls.N//2:
2188 raise RuntimeError
2189 barrier.wait()
2190 results1.append(True)
2191 except threading.BrokenBarrierError:
2192 results2.append(True)
2193 except RuntimeError:
2194 barrier.abort()
2195 # Synchronize and reset the barrier. Must synchronize first so
2196 # that everyone has left it when we reset, and after so that no
2197 # one enters it before the reset.
2198 if barrier2.wait() == cls.N//2:
2199 barrier.reset()
2200 barrier2.wait()
2201 barrier.wait()
2202 results3.append(True)
2203
2204 def test_abort_and_reset(self):
2205 """
2206 Test that a barrier can be reset after being broken.
2207 """
2208 results1 = self.DummyList()
2209 results2 = self.DummyList()
2210 results3 = self.DummyList()
2211 barrier2 = self.Barrier(self.N)
2212
2213 self.run_threads(self._test_abort_and_reset_f,
2214 (self.barrier, barrier2, results1, results2, results3))
2215 self.assertEqual(len(results1), 0)
2216 self.assertEqual(len(results2), self.N-1)
2217 self.assertEqual(len(results3), self.N)
2218
2219 @classmethod
2220 def _test_timeout_f(cls, barrier, results):
2221 i = barrier.wait()
2222 if i == cls.N//2:
2223 # One thread is late!
2224 time.sleep(1.0)
2225 try:
2226 barrier.wait(0.5)
2227 except threading.BrokenBarrierError:
2228 results.append(True)
2229
2230 def test_timeout(self):
2231 """
2232 Test wait(timeout)
2233 """
2234 results = self.DummyList()
2235 self.run_threads(self._test_timeout_f, (self.barrier, results))
2236 self.assertEqual(len(results), self.barrier.parties)
2237
2238 @classmethod
2239 def _test_default_timeout_f(cls, barrier, results):
2240 i = barrier.wait(cls.defaultTimeout)
2241 if i == cls.N//2:
2242 # One thread is later than the default timeout
2243 time.sleep(1.0)
2244 try:
2245 barrier.wait()
2246 except threading.BrokenBarrierError:
2247 results.append(True)
2248
2249 def test_default_timeout(self):
2250 """
2251 Test the barrier's default timeout
2252 """
2253 barrier = self.Barrier(self.N, timeout=0.5)
2254 results = self.DummyList()
2255 self.run_threads(self._test_default_timeout_f, (barrier, results))
2256 self.assertEqual(len(results), barrier.parties)
2257
2258 def test_single_thread(self):
2259 b = self.Barrier(1)
2260 b.wait()
2261 b.wait()
2262
2263 @classmethod
2264 def _test_thousand_f(cls, barrier, passes, conn, lock):
2265 for i in range(passes):
2266 barrier.wait()
2267 with lock:
2268 conn.send(i)
2269
2270 def test_thousand(self):
2271 if self.TYPE == 'manager':
2272 self.skipTest('test not appropriate for {}'.format(self.TYPE))
2273 passes = 1000
2274 lock = self.Lock()
2275 conn, child_conn = self.Pipe(False)
2276 for j in range(self.N):
2277 p = self.Process(target=self._test_thousand_f,
2278 args=(self.barrier, passes, child_conn, lock))
2279 p.start()
2280 self.addCleanup(p.join)
2281
2282 for i in range(passes):
2283 for j in range(self.N):
2284 self.assertEqual(conn.recv(), i)
2285
2286 #
2287 #
2288 #
2289
2290 class _TestValue(BaseTestCase):
2291
2292 ALLOWED_TYPES = ('processes',)
2293
2294 codes_values = [
2295 ('i', 4343, 24234),
2296 ('d', 3.625, -4.25),
2297 ('h', -232, 234),
2298 ('q', 2 ** 33, 2 ** 34),
2299 ('c', latin('x'), latin('y'))
2300 ]
2301
2302 def setUp(self):
2303 if not HAS_SHAREDCTYPES:
2304 self.skipTest("requires multiprocessing.sharedctypes")
2305
2306 @classmethod
2307 def _test(cls, values):
2308 for sv, cv in zip(values, cls.codes_values):
2309 sv.value = cv[2]
2310
2311
2312 def test_value(self, raw=False):
2313 if raw:
2314 values = [self.RawValue(code, value)
2315 for code, value, _ in self.codes_values]
2316 else:
2317 values = [self.Value(code, value)
2318 for code, value, _ in self.codes_values]
2319
2320 for sv, cv in zip(values, self.codes_values):
2321 self.assertEqual(sv.value, cv[1])
2322
2323 proc = self.Process(target=self._test, args=(values,))
2324 proc.daemon = True
2325 proc.start()
2326 proc.join()
2327
2328 for sv, cv in zip(values, self.codes_values):
2329 self.assertEqual(sv.value, cv[2])
2330
2331 def test_rawvalue(self):
2332 self.test_value(raw=True)
2333
2334 def test_getobj_getlock(self):
2335 val1 = self.Value('i', 5)
2336 lock1 = val1.get_lock()
2337 obj1 = val1.get_obj()
2338
2339 val2 = self.Value('i', 5, lock=None)
2340 lock2 = val2.get_lock()
2341 obj2 = val2.get_obj()
2342
2343 lock = self.Lock()
2344 val3 = self.Value('i', 5, lock=lock)
2345 lock3 = val3.get_lock()
2346 obj3 = val3.get_obj()
2347 self.assertEqual(lock, lock3)
2348
2349 arr4 = self.Value('i', 5, lock=False)
2350 self.assertFalse(hasattr(arr4, 'get_lock'))
2351 self.assertFalse(hasattr(arr4, 'get_obj'))
2352
2353 self.assertRaises(AttributeError, self.Value, 'i', 5, lock='navalue')
2354
2355 arr5 = self.RawValue('i', 5)
2356 self.assertFalse(hasattr(arr5, 'get_lock'))
2357 self.assertFalse(hasattr(arr5, 'get_obj'))
2358
2359
2360 class _TestArray(BaseTestCase):
2361
2362 ALLOWED_TYPES = ('processes',)
2363
2364 @classmethod
2365 def f(cls, seq):
2366 for i in range(1, len(seq)):
2367 seq[i] += seq[i-1]
2368
2369 @unittest.skipIf(c_int is None, "requires _ctypes")
2370 def test_array(self, raw=False):
2371 seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831]
2372 if raw:
2373 arr = self.RawArray('i', seq)
2374 else:
2375 arr = self.Array('i', seq)
2376
2377 self.assertEqual(len(arr), len(seq))
2378 self.assertEqual(arr[3], seq[3])
2379 self.assertEqual(list(arr[2:7]), list(seq[2:7]))
2380
2381 arr[4:8] = seq[4:8] = array.array('i', [1, 2, 3, 4])
2382
2383 self.assertEqual(list(arr[:]), seq)
2384
2385 self.f(seq)
2386
2387 p = self.Process(target=self.f, args=(arr,))
2388 p.daemon = True
2389 p.start()
2390 p.join()
2391
2392 self.assertEqual(list(arr[:]), seq)
2393
2394 @unittest.skipIf(c_int is None, "requires _ctypes")
2395 def test_array_from_size(self):
2396 size = 10
2397 # Test for zeroing (see issue #11675).
2398 # The repetition below strengthens the test by increasing the chances
2399 # of previously allocated non-zero memory being used for the new array
2400 # on the 2nd and 3rd loops.
2401 for _ in range(3):
2402 arr = self.Array('i', size)
2403 self.assertEqual(len(arr), size)
2404 self.assertEqual(list(arr), [0] * size)
2405 arr[:] = range(10)
2406 self.assertEqual(list(arr), list(range(10)))
2407 del arr
2408
2409 @unittest.skipIf(c_int is None, "requires _ctypes")
2410 def test_rawarray(self):
2411 self.test_array(raw=True)
2412
2413 @unittest.skipIf(c_int is None, "requires _ctypes")
2414 def test_getobj_getlock_obj(self):
2415 arr1 = self.Array('i', list(range(10)))
2416 lock1 = arr1.get_lock()
2417 obj1 = arr1.get_obj()
2418
2419 arr2 = self.Array('i', list(range(10)), lock=None)
2420 lock2 = arr2.get_lock()
2421 obj2 = arr2.get_obj()
2422
2423 lock = self.Lock()
2424 arr3 = self.Array('i', list(range(10)), lock=lock)
2425 lock3 = arr3.get_lock()
2426 obj3 = arr3.get_obj()
2427 self.assertEqual(lock, lock3)
2428
2429 arr4 = self.Array('i', range(10), lock=False)
2430 self.assertFalse(hasattr(arr4, 'get_lock'))
2431 self.assertFalse(hasattr(arr4, 'get_obj'))
2432 self.assertRaises(AttributeError,
2433 self.Array, 'i', range(10), lock='notalock')
2434
2435 arr5 = self.RawArray('i', range(10))
2436 self.assertFalse(hasattr(arr5, 'get_lock'))
2437 self.assertFalse(hasattr(arr5, 'get_obj'))
2438
2439 #
2440 #
2441 #
2442
2443 class _TestContainers(BaseTestCase):
2444
2445 ALLOWED_TYPES = ('manager',)
2446
2447 def test_list(self):
2448 a = self.list(list(range(10)))
2449 self.assertEqual(a[:], list(range(10)))
2450
2451 b = self.list()
2452 self.assertEqual(b[:], [])
2453
2454 b.extend(list(range(5)))
2455 self.assertEqual(b[:], list(range(5)))
2456
2457 self.assertEqual(b[2], 2)
2458 self.assertEqual(b[2:10], [2,3,4])
2459
2460 b *= 2
2461 self.assertEqual(b[:], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
2462
2463 self.assertEqual(b + [5, 6], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6])
2464
2465 self.assertEqual(a[:], list(range(10)))
2466
2467 d = [a, b]
2468 e = self.list(d)
2469 self.assertEqual(
2470 [element[:] for element in e],
2471 [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
2472 )
2473
2474 f = self.list([a])
2475 a.append('hello')
2476 self.assertEqual(f[0][:], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'hello'])
2477
2478 def test_list_iter(self):
2479 a = self.list(list(range(10)))
2480 it = iter(a)
2481 self.assertEqual(list(it), list(range(10)))
2482 self.assertEqual(list(it), []) # exhausted
2483 # list modified during iteration
2484 it = iter(a)
2485 a[0] = 100
2486 self.assertEqual(next(it), 100)
2487
2488 def test_list_proxy_in_list(self):
2489 a = self.list([self.list(range(3)) for _i in range(3)])
2490 self.assertEqual([inner[:] for inner in a], [[0, 1, 2]] * 3)
2491
2492 a[0][-1] = 55
2493 self.assertEqual(a[0][:], [0, 1, 55])
2494 for i in range(1, 3):
2495 self.assertEqual(a[i][:], [0, 1, 2])
2496
2497 self.assertEqual(a[1].pop(), 2)
2498 self.assertEqual(len(a[1]), 2)
2499 for i in range(0, 3, 2):
2500 self.assertEqual(len(a[i]), 3)
2501
2502 del a
2503
2504 b = self.list()
2505 b.append(b)
2506 del b
2507
2508 def test_dict(self):
2509 d = self.dict()
2510 indices = list(range(65, 70))
2511 for i in indices:
2512 d[i] = chr(i)
2513 self.assertEqual(d.copy(), dict((i, chr(i)) for i in indices))
2514 self.assertEqual(sorted(d.keys()), indices)
2515 self.assertEqual(sorted(d.values()), [chr(i) for i in indices])
2516 self.assertEqual(sorted(d.items()), [(i, chr(i)) for i in indices])
2517
2518 def test_dict_iter(self):
2519 d = self.dict()
2520 indices = list(range(65, 70))
2521 for i in indices:
2522 d[i] = chr(i)
2523 it = iter(d)
2524 self.assertEqual(list(it), indices)
2525 self.assertEqual(list(it), []) # exhausted
2526 # dictionary changed size during iteration
2527 it = iter(d)
2528 d.clear()
2529 self.assertRaises(RuntimeError, next, it)
2530
2531 def test_dict_proxy_nested(self):
2532 pets = self.dict(ferrets=2, hamsters=4)
2533 supplies = self.dict(water=10, feed=3)
2534 d = self.dict(pets=pets, supplies=supplies)
2535
2536 self.assertEqual(supplies['water'], 10)
2537 self.assertEqual(d['supplies']['water'], 10)
2538
2539 d['supplies']['blankets'] = 5
2540 self.assertEqual(supplies['blankets'], 5)
2541 self.assertEqual(d['supplies']['blankets'], 5)
2542
2543 d['supplies']['water'] = 7
2544 self.assertEqual(supplies['water'], 7)
2545 self.assertEqual(d['supplies']['water'], 7)
2546
2547 del pets
2548 del supplies
2549 self.assertEqual(d['pets']['ferrets'], 2)
2550 d['supplies']['blankets'] = 11
2551 self.assertEqual(d['supplies']['blankets'], 11)
2552
2553 pets = d['pets']
2554 supplies = d['supplies']
2555 supplies['water'] = 7
2556 self.assertEqual(supplies['water'], 7)
2557 self.assertEqual(d['supplies']['water'], 7)
2558
2559 d.clear()
2560 self.assertEqual(len(d), 0)
2561 self.assertEqual(supplies['water'], 7)
2562 self.assertEqual(pets['hamsters'], 4)
2563
2564 l = self.list([pets, supplies])
2565 l[0]['marmots'] = 1
2566 self.assertEqual(pets['marmots'], 1)
2567 self.assertEqual(l[0]['marmots'], 1)
2568
2569 del pets
2570 del supplies
2571 self.assertEqual(l[0]['marmots'], 1)
2572
2573 outer = self.list([[88, 99], l])
2574 self.assertIsInstance(outer[0], list) # Not a ListProxy
2575 self.assertEqual(outer[-1][-1]['feed'], 3)
2576
2577 def test_nested_queue(self):
2578 a = self.list() # Test queue inside list
2579 a.append(self.Queue())
2580 a[0].put(123)
2581 self.assertEqual(a[0].get(), 123)
2582 b = self.dict() # Test queue inside dict
2583 b[0] = self.Queue()
2584 b[0].put(456)
2585 self.assertEqual(b[0].get(), 456)
2586
2587 def test_namespace(self):
2588 n = self.Namespace()
2589 n.name = 'Bob'
2590 n.job = 'Builder'
2591 n._hidden = 'hidden'
2592 self.assertEqual((n.name, n.job), ('Bob', 'Builder'))
2593 del n.job
2594 self.assertEqual(str(n), "Namespace(name='Bob')")
2595 self.assertTrue(hasattr(n, 'name'))
2596 self.assertTrue(not hasattr(n, 'job'))
2597
2598 #
2599 #
2600 #
2601
2602 def sqr(x, wait=0.0, event=None):
2603 if event is None:
2604 time.sleep(wait)
2605 else:
2606 event.wait(wait)
2607 return x*x
2608
2609 def mul(x, y):
2610 return x*y
2611
2612 def raise_large_valuerror(wait):
2613 time.sleep(wait)
2614 raise ValueError("x" * 1024**2)
2615
2616 def identity(x):
2617 return x
2618
2619 class CountedObject(object):
2620 n_instances = 0
2621
2622 def __new__(cls):
2623 cls.n_instances += 1
2624 return object.__new__(cls)
2625
2626 def __del__(self):
2627 type(self).n_instances -= 1
2628
2629 class SayWhenError(ValueError): pass
2630
2631 def exception_throwing_generator(total, when):
2632 if when == -1:
2633 raise SayWhenError("Somebody said when")
2634 for i in range(total):
2635 if i == when:
2636 raise SayWhenError("Somebody said when")
2637 yield i
2638
2639
2640 class _TestPool(BaseTestCase):
2641
2642 @classmethod
2643 def setUpClass(cls):
2644 super().setUpClass()
2645 cls.pool = cls.Pool(4)
2646
2647 @classmethod
2648 def tearDownClass(cls):
2649 cls.pool.terminate()
2650 cls.pool.join()
2651 cls.pool = None
2652 super().tearDownClass()
2653
2654 def test_apply(self):
2655 papply = self.pool.apply
2656 self.assertEqual(papply(sqr, (5,)), sqr(5))
2657 self.assertEqual(papply(sqr, (), {'x':3}), sqr(x=3))
2658
2659 def test_map(self):
2660 pmap = self.pool.map
2661 self.assertEqual(pmap(sqr, list(range(10))), list(map(sqr, list(range(10)))))
2662 self.assertEqual(pmap(sqr, list(range(100)), chunksize=20),
2663 list(map(sqr, list(range(100)))))
2664
2665 def test_starmap(self):
2666 psmap = self.pool.starmap
2667 tuples = list(zip(range(10), range(9,-1, -1)))
2668 self.assertEqual(psmap(mul, tuples),
2669 list(itertools.starmap(mul, tuples)))
2670 tuples = list(zip(range(100), range(99,-1, -1)))
2671 self.assertEqual(psmap(mul, tuples, chunksize=20),
2672 list(itertools.starmap(mul, tuples)))
2673
2674 def test_starmap_async(self):
2675 tuples = list(zip(range(100), range(99,-1, -1)))
2676 self.assertEqual(self.pool.starmap_async(mul, tuples).get(),
2677 list(itertools.starmap(mul, tuples)))
2678
2679 def test_map_async(self):
2680 self.assertEqual(self.pool.map_async(sqr, list(range(10))).get(),
2681 list(map(sqr, list(range(10)))))
2682
2683 def test_map_async_callbacks(self):
2684 call_args = self.manager.list() if self.TYPE == 'manager' else []
2685 self.pool.map_async(int, ['1'],
2686 callback=call_args.append,
2687 error_callback=call_args.append).wait()
2688 self.assertEqual(1, len(call_args))
2689 self.assertEqual([1], call_args[0])
2690 self.pool.map_async(int, ['a'],
2691 callback=call_args.append,
2692 error_callback=call_args.append).wait()
2693 self.assertEqual(2, len(call_args))
2694 self.assertIsInstance(call_args[1], ValueError)
2695
2696 def test_map_unplicklable(self):
2697 # Issue #19425 -- failure to pickle should not cause a hang
2698 if self.TYPE == 'threads':
2699 self.skipTest('test not appropriate for {}'.format(self.TYPE))
2700 class A(object):
2701 def __reduce__(self):
2702 raise RuntimeError('cannot pickle')
2703 with self.assertRaises(RuntimeError):
2704 self.pool.map(sqr, [A()]*10)
2705
2706 def test_map_chunksize(self):
2707 try:
2708 self.pool.map_async(sqr, [], chunksize=1).get(timeout=TIMEOUT1)
2709 except multiprocessing.TimeoutError:
2710 self.fail("pool.map_async with chunksize stalled on null list")
2711
2712 def test_map_handle_iterable_exception(self):
2713 if self.TYPE == 'manager':
2714 self.skipTest('test not appropriate for {}'.format(self.TYPE))
2715
2716 # SayWhenError seen at the very first of the iterable
2717 with self.assertRaises(SayWhenError):
2718 self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
2719 # again, make sure it's reentrant
2720 with self.assertRaises(SayWhenError):
2721 self.pool.map(sqr, exception_throwing_generator(1, -1), 1)
2722
2723 with self.assertRaises(SayWhenError):
2724 self.pool.map(sqr, exception_throwing_generator(10, 3), 1)
2725
2726 class SpecialIterable:
2727 def __iter__(self):
2728 return self
2729 def __next__(self):
2730 raise SayWhenError
2731 def __len__(self):
2732 return 1
2733 with self.assertRaises(SayWhenError):
2734 self.pool.map(sqr, SpecialIterable(), 1)
2735 with self.assertRaises(SayWhenError):
2736 self.pool.map(sqr, SpecialIterable(), 1)
2737
2738 def test_async(self):
2739 res = self.pool.apply_async(sqr, (7, TIMEOUT1,))
2740 get = TimingWrapper(res.get)
2741 self.assertEqual(get(), 49)
2742 self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1)
2743
2744 def test_async_timeout(self):
2745 p = self.Pool(3)
2746 try:
2747 event = threading.Event() if self.TYPE == 'threads' else None
2748 res = p.apply_async(sqr, (6, TIMEOUT2 + support.SHORT_TIMEOUT, event))
2749 get = TimingWrapper(res.get)
2750 self.assertRaises(multiprocessing.TimeoutError, get, timeout=TIMEOUT2)
2751 self.assertTimingAlmostEqual(get.elapsed, TIMEOUT2)
2752 finally:
2753 if event is not None:
2754 event.set()
2755 p.terminate()
2756 p.join()
2757
2758 def test_imap(self):
2759 it = self.pool.imap(sqr, list(range(10)))
2760 self.assertEqual(list(it), list(map(sqr, list(range(10)))))
2761
2762 it = self.pool.imap(sqr, list(range(10)))
2763 for i in range(10):
2764 self.assertEqual(next(it), i*i)
2765 self.assertRaises(StopIteration, it.__next__)
2766
2767 it = self.pool.imap(sqr, list(range(1000)), chunksize=100)
2768 for i in range(1000):
2769 self.assertEqual(next(it), i*i)
2770 self.assertRaises(StopIteration, it.__next__)
2771
2772 def test_imap_handle_iterable_exception(self):
2773 if self.TYPE == 'manager':
2774 self.skipTest('test not appropriate for {}'.format(self.TYPE))
2775
2776 # SayWhenError seen at the very first of the iterable
2777 it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
2778 self.assertRaises(SayWhenError, it.__next__)
2779 # again, make sure it's reentrant
2780 it = self.pool.imap(sqr, exception_throwing_generator(1, -1), 1)
2781 self.assertRaises(SayWhenError, it.__next__)
2782
2783 it = self.pool.imap(sqr, exception_throwing_generator(10, 3), 1)
2784 for i in range(3):
2785 self.assertEqual(next(it), i*i)
2786 self.assertRaises(SayWhenError, it.__next__)
2787
2788 # SayWhenError seen at start of problematic chunk's results
2789 it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 2)
2790 for i in range(6):
2791 self.assertEqual(next(it), i*i)
2792 self.assertRaises(SayWhenError, it.__next__)
2793 it = self.pool.imap(sqr, exception_throwing_generator(20, 7), 4)
2794 for i in range(4):
2795 self.assertEqual(next(it), i*i)
2796 self.assertRaises(SayWhenError, it.__next__)
2797
2798 def test_imap_unordered(self):
2799 it = self.pool.imap_unordered(sqr, list(range(10)))
2800 self.assertEqual(sorted(it), list(map(sqr, list(range(10)))))
2801
2802 it = self.pool.imap_unordered(sqr, list(range(1000)), chunksize=100)
2803 self.assertEqual(sorted(it), list(map(sqr, list(range(1000)))))
2804
2805 def test_imap_unordered_handle_iterable_exception(self):
2806 if self.TYPE == 'manager':
2807 self.skipTest('test not appropriate for {}'.format(self.TYPE))
2808
2809 # SayWhenError seen at the very first of the iterable
2810 it = self.pool.imap_unordered(sqr,
2811 exception_throwing_generator(1, -1),
2812 1)
2813 self.assertRaises(SayWhenError, it.__next__)
2814 # again, make sure it's reentrant
2815 it = self.pool.imap_unordered(sqr,
2816 exception_throwing_generator(1, -1),
2817 1)
2818 self.assertRaises(SayWhenError, it.__next__)
2819
2820 it = self.pool.imap_unordered(sqr,
2821 exception_throwing_generator(10, 3),
2822 1)
2823 expected_values = list(map(sqr, list(range(10))))
2824 with self.assertRaises(SayWhenError):
2825 # imap_unordered makes it difficult to anticipate the SayWhenError
2826 for i in range(10):
2827 value = next(it)
2828 self.assertIn(value, expected_values)
2829 expected_values.remove(value)
2830
2831 it = self.pool.imap_unordered(sqr,
2832 exception_throwing_generator(20, 7),
2833 2)
2834 expected_values = list(map(sqr, list(range(20))))
2835 with self.assertRaises(SayWhenError):
2836 for i in range(20):
2837 value = next(it)
2838 self.assertIn(value, expected_values)
2839 expected_values.remove(value)
2840
2841 def test_make_pool(self):
2842 expected_error = (RemoteError if self.TYPE == 'manager'
2843 else ValueError)
2844
2845 self.assertRaises(expected_error, self.Pool, -1)
2846 self.assertRaises(expected_error, self.Pool, 0)
2847
2848 if self.TYPE != 'manager':
2849 p = self.Pool(3)
2850 try:
2851 self.assertEqual(3, len(p._pool))
2852 finally:
2853 p.close()
2854 p.join()
2855
2856 def test_terminate(self):
2857 # Simulate slow tasks which take "forever" to complete
2858 sleep_time = support.LONG_TIMEOUT
2859
2860 if self.TYPE == 'threads':
2861 # Thread pool workers can't be forced to quit, so if the first
2862 # task starts early enough, we will end up waiting for it.
2863 # Sleep for a shorter time, so the test doesn't block.
2864 sleep_time = 1
2865
2866 p = self.Pool(3)
2867 args = [sleep_time for i in range(10_000)]
2868 result = p.map_async(time.sleep, args, chunksize=1)
2869 time.sleep(0.2) # give some tasks a chance to start
2870 p.terminate()
2871 p.join()
2872
2873 def test_empty_iterable(self):
2874 # See Issue 12157
2875 p = self.Pool(1)
2876
2877 self.assertEqual(p.map(sqr, []), [])
2878 self.assertEqual(list(p.imap(sqr, [])), [])
2879 self.assertEqual(list(p.imap_unordered(sqr, [])), [])
2880 self.assertEqual(p.map_async(sqr, []).get(), [])
2881
2882 p.close()
2883 p.join()
2884
2885 def test_context(self):
2886 if self.TYPE == 'processes':
2887 L = list(range(10))
2888 expected = [sqr(i) for i in L]
2889 with self.Pool(2) as p:
2890 r = p.map_async(sqr, L)
2891 self.assertEqual(r.get(), expected)
2892 p.join()
2893 self.assertRaises(ValueError, p.map_async, sqr, L)
2894
2895 @classmethod
2896 def _test_traceback(cls):
2897 raise RuntimeError(123) # some comment
2898
2899 def test_traceback(self):
2900 # We want ensure that the traceback from the child process is
2901 # contained in the traceback raised in the main process.
2902 if self.TYPE == 'processes':
2903 with self.Pool(1) as p:
2904 try:
2905 p.apply(self._test_traceback)
2906 except Exception as e:
2907 exc = e
2908 else:
2909 self.fail('expected RuntimeError')
2910 p.join()
2911 self.assertIs(type(exc), RuntimeError)
2912 self.assertEqual(exc.args, (123,))
2913 cause = exc.__cause__
2914 self.assertIs(type(cause), multiprocessing.pool.RemoteTraceback)
2915 self.assertIn('raise RuntimeError(123) # some comment', cause.tb)
2916
2917 with test.support.captured_stderr() as f1:
2918 try:
2919 raise exc
2920 except RuntimeError:
2921 sys.excepthook(*sys.exc_info())
2922 self.assertIn('raise RuntimeError(123) # some comment',
2923 f1.getvalue())
2924 # _helper_reraises_exception should not make the error
2925 # a remote exception
2926 with self.Pool(1) as p:
2927 try:
2928 p.map(sqr, exception_throwing_generator(1, -1), 1)
2929 except Exception as e:
2930 exc = e
2931 else:
2932 self.fail('expected SayWhenError')
2933 self.assertIs(type(exc), SayWhenError)
2934 self.assertIs(exc.__cause__, None)
2935 p.join()
2936
2937 @classmethod
2938 def _test_wrapped_exception(cls):
2939 raise RuntimeError('foo')
2940
2941 def test_wrapped_exception(self):
2942 # Issue #20980: Should not wrap exception when using thread pool
2943 with self.Pool(1) as p:
2944 with self.assertRaises(RuntimeError):
2945 p.apply(self._test_wrapped_exception)
2946 p.join()
2947
2948 def test_map_no_failfast(self):
2949 # Issue #23992: the fail-fast behaviour when an exception is raised
2950 # during map() would make Pool.join() deadlock, because a worker
2951 # process would fill the result queue (after the result handler thread
2952 # terminated, hence not draining it anymore).
2953
2954 t_start = time.monotonic()
2955
2956 with self.assertRaises(ValueError):
2957 with self.Pool(2) as p:
2958 try:
2959 p.map(raise_large_valuerror, [0, 1])
2960 finally:
2961 time.sleep(0.5)
2962 p.close()
2963 p.join()
2964
2965 # check that we indeed waited for all jobs
2966 self.assertGreater(time.monotonic() - t_start, 0.9)
2967
2968 def test_release_task_refs(self):
2969 # Issue #29861: task arguments and results should not be kept
2970 # alive after we are done with them.
2971 objs = [CountedObject() for i in range(10)]
2972 refs = [weakref.ref(o) for o in objs]
2973 self.pool.map(identity, objs)
2974
2975 del objs
2976 time.sleep(DELTA) # let threaded cleanup code run
2977 support.gc_collect() # For PyPy or other GCs.
2978 self.assertEqual(set(wr() for wr in refs), {None})
2979 # With a process pool, copies of the objects are returned, check
2980 # they were released too.
2981 self.assertEqual(CountedObject.n_instances, 0)
2982
2983 def test_enter(self):
2984 if self.TYPE == 'manager':
2985 self.skipTest("test not applicable to manager")
2986
2987 pool = self.Pool(1)
2988 with pool:
2989 pass
2990 # call pool.terminate()
2991 # pool is no longer running
2992
2993 with self.assertRaises(ValueError):
2994 # bpo-35477: pool.__enter__() fails if the pool is not running
2995 with pool:
2996 pass
2997 pool.join()
2998
2999 def test_resource_warning(self):
3000 if self.TYPE == 'manager':
3001 self.skipTest("test not applicable to manager")
3002
3003 pool = self.Pool(1)
3004 pool.terminate()
3005 pool.join()
3006
3007 # force state to RUN to emit ResourceWarning in __del__()
3008 pool._state = multiprocessing.pool.RUN
3009
3010 with warnings_helper.check_warnings(
3011 ('unclosed running multiprocessing pool', ResourceWarning)):
3012 pool = None
3013 support.gc_collect()
3014
3015 def raising():
3016 raise KeyError("key")
3017
3018 def unpickleable_result():
3019 return lambda: 42
3020
3021 class _TestPoolWorkerErrors(BaseTestCase):
3022 ALLOWED_TYPES = ('processes', )
3023
3024 def test_async_error_callback(self):
3025 p = multiprocessing.Pool(2)
3026
3027 scratchpad = [None]
3028 def errback(exc):
3029 scratchpad[0] = exc
3030
3031 res = p.apply_async(raising, error_callback=errback)
3032 self.assertRaises(KeyError, res.get)
3033 self.assertTrue(scratchpad[0])
3034 self.assertIsInstance(scratchpad[0], KeyError)
3035
3036 p.close()
3037 p.join()
3038
3039 def test_unpickleable_result(self):
3040 from multiprocessing.pool import MaybeEncodingError
3041 p = multiprocessing.Pool(2)
3042
3043 # Make sure we don't lose pool processes because of encoding errors.
3044 for iteration in range(20):
3045
3046 scratchpad = [None]
3047 def errback(exc):
3048 scratchpad[0] = exc
3049
3050 res = p.apply_async(unpickleable_result, error_callback=errback)
3051 self.assertRaises(MaybeEncodingError, res.get)
3052 wrapped = scratchpad[0]
3053 self.assertTrue(wrapped)
3054 self.assertIsInstance(scratchpad[0], MaybeEncodingError)
3055 self.assertIsNotNone(wrapped.exc)
3056 self.assertIsNotNone(wrapped.value)
3057
3058 p.close()
3059 p.join()
3060
3061 class _TestPoolWorkerLifetime(BaseTestCase):
3062 ALLOWED_TYPES = ('processes', )
3063
3064 def test_pool_worker_lifetime(self):
3065 p = multiprocessing.Pool(3, maxtasksperchild=10)
3066 self.assertEqual(3, len(p._pool))
3067 origworkerpids = [w.pid for w in p._pool]
3068 # Run many tasks so each worker gets replaced (hopefully)
3069 results = []
3070 for i in range(100):
3071 results.append(p.apply_async(sqr, (i, )))
3072 # Fetch the results and verify we got the right answers,
3073 # also ensuring all the tasks have completed.
3074 for (j, res) in enumerate(results):
3075 self.assertEqual(res.get(), sqr(j))
3076 # Refill the pool
3077 p._repopulate_pool()
3078 # Wait until all workers are alive
3079 # (countdown * DELTA = 5 seconds max startup process time)
3080 countdown = 50
3081 while countdown and not all(w.is_alive() for w in p._pool):
3082 countdown -= 1
3083 time.sleep(DELTA)
3084 finalworkerpids = [w.pid for w in p._pool]
3085 # All pids should be assigned. See issue #7805.
3086 self.assertNotIn(None, origworkerpids)
3087 self.assertNotIn(None, finalworkerpids)
3088 # Finally, check that the worker pids have changed
3089 self.assertNotEqual(sorted(origworkerpids), sorted(finalworkerpids))
3090 p.close()
3091 p.join()
3092
3093 def test_pool_worker_lifetime_early_close(self):
3094 # Issue #10332: closing a pool whose workers have limited lifetimes
3095 # before all the tasks completed would make join() hang.
3096 p = multiprocessing.Pool(3, maxtasksperchild=1)
3097 results = []
3098 for i in range(6):
3099 results.append(p.apply_async(sqr, (i, 0.3)))
3100 p.close()
3101 p.join()
3102 # check the results
3103 for (j, res) in enumerate(results):
3104 self.assertEqual(res.get(), sqr(j))
3105
3106 def test_pool_maxtasksperchild_invalid(self):
3107 for value in [0, -1, 0.5, "12"]:
3108 with self.assertRaises(ValueError):
3109 multiprocessing.Pool(3, maxtasksperchild=value)
3110
3111 def test_worker_finalization_via_atexit_handler_of_multiprocessing(self):
3112 # tests cases against bpo-38744 and bpo-39360
3113 cmd = '''if 1:
3114 from multiprocessing import Pool
3115 problem = None
3116 class A:
3117 def __init__(self):
3118 self.pool = Pool(processes=1)
3119 def test():
3120 global problem
3121 problem = A()
3122 problem.pool.map(float, tuple(range(10)))
3123 if __name__ == "__main__":
3124 test()
3125 '''
3126 rc, out, err = test.support.script_helper.assert_python_ok('-c', cmd)
3127 self.assertEqual(rc, 0)
3128
3129 #
3130 # Test of creating a customized manager class
3131 #
3132
3133 from multiprocessing.managers import BaseManager, BaseProxy, RemoteError
3134
3135 class FooBar(object):
3136 def f(self):
3137 return 'f()'
3138 def g(self):
3139 raise ValueError
3140 def _h(self):
3141 return '_h()'
3142
3143 def baz():
3144 for i in range(10):
3145 yield i*i
3146
3147 class IteratorProxy(BaseProxy):
3148 _exposed_ = ('__next__',)
3149 def __iter__(self):
3150 return self
3151 def __next__(self):
3152 return self._callmethod('__next__')
3153
3154 class MyManager(BaseManager):
3155 pass
3156
3157 MyManager.register('Foo', callable=FooBar)
3158 MyManager.register('Bar', callable=FooBar, exposed=('f', '_h'))
3159 MyManager.register('baz', callable=baz, proxytype=IteratorProxy)
3160
3161
3162 class _TestMyManager(BaseTestCase):
3163
3164 ALLOWED_TYPES = ('manager',)
3165
3166 @support.skip_if_sanitizer('TSan: leaks threads', thread=True)
3167 def test_mymanager(self):
3168 manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT)
3169 manager.start()
3170 self.common(manager)
3171 manager.shutdown()
3172
3173 # bpo-30356: BaseManager._finalize_manager() sends SIGTERM
3174 # to the manager process if it takes longer than 1 second to stop,
3175 # which happens on slow buildbots.
3176 self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
3177
3178 @support.skip_if_sanitizer('TSan: leaks threads', thread=True)
3179 def test_mymanager_context(self):
3180 manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT)
3181 with manager:
3182 self.common(manager)
3183 # bpo-30356: BaseManager._finalize_manager() sends SIGTERM
3184 # to the manager process if it takes longer than 1 second to stop,
3185 # which happens on slow buildbots.
3186 self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM))
3187
3188 @support.skip_if_sanitizer('TSan: leaks threads', thread=True)
3189 def test_mymanager_context_prestarted(self):
3190 manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT)
3191 manager.start()
3192 with manager:
3193 self.common(manager)
3194 self.assertEqual(manager._process.exitcode, 0)
3195
3196 def common(self, manager):
3197 foo = manager.Foo()
3198 bar = manager.Bar()
3199 baz = manager.baz()
3200
3201 foo_methods = [name for name in ('f', 'g', '_h') if hasattr(foo, name)]
3202 bar_methods = [name for name in ('f', 'g', '_h') if hasattr(bar, name)]
3203
3204 self.assertEqual(foo_methods, ['f', 'g'])
3205 self.assertEqual(bar_methods, ['f', '_h'])
3206
3207 self.assertEqual(foo.f(), 'f()')
3208 self.assertRaises(ValueError, foo.g)
3209 self.assertEqual(foo._callmethod('f'), 'f()')
3210 self.assertRaises(RemoteError, foo._callmethod, '_h')
3211
3212 self.assertEqual(bar.f(), 'f()')
3213 self.assertEqual(bar._h(), '_h()')
3214 self.assertEqual(bar._callmethod('f'), 'f()')
3215 self.assertEqual(bar._callmethod('_h'), '_h()')
3216
3217 self.assertEqual(list(baz), [i*i for i in range(10)])
3218
3219
3220 #
3221 # Test of connecting to a remote server and using xmlrpclib for serialization
3222 #
3223
3224 _queue = pyqueue.Queue()
3225 def get_queue():
3226 return _queue
3227
3228 class QueueManager(BaseManager):
3229 '''manager class used by server process'''
3230 QueueManager.register('get_queue', callable=get_queue)
3231
3232 class QueueManager2(BaseManager):
3233 '''manager class which specifies the same interface as QueueManager'''
3234 QueueManager2.register('get_queue')
3235
3236
3237 SERIALIZER = 'xmlrpclib'
3238
3239 class _TestRemoteManager(BaseTestCase):
3240
3241 ALLOWED_TYPES = ('manager',)
3242 values = ['hello world', None, True, 2.25,
3243 'hall\xe5 v\xe4rlden',
3244 '\u043f\u0440\u0438\u0432\u0456\u0442 \u0441\u0432\u0456\u0442',
3245 b'hall\xe5 v\xe4rlden',
3246 ]
3247 result = values[:]
3248
3249 @classmethod
3250 def _putter(cls, address, authkey):
3251 manager = QueueManager2(
3252 address=address, authkey=authkey, serializer=SERIALIZER,
3253 shutdown_timeout=SHUTDOWN_TIMEOUT)
3254 manager.connect()
3255 queue = manager.get_queue()
3256 # Note that xmlrpclib will deserialize object as a list not a tuple
3257 queue.put(tuple(cls.values))
3258
3259 @support.skip_if_sanitizer('TSan: leaks threads', thread=True)
3260 def test_remote(self):
3261 authkey = os.urandom(32)
3262
3263 manager = QueueManager(
3264 address=(socket_helper.HOST, 0), authkey=authkey, serializer=SERIALIZER,
3265 shutdown_timeout=SHUTDOWN_TIMEOUT)
3266 manager.start()
3267 self.addCleanup(manager.shutdown)
3268
3269 p = self.Process(target=self._putter, args=(manager.address, authkey))
3270 p.daemon = True
3271 p.start()
3272
3273 manager2 = QueueManager2(
3274 address=manager.address, authkey=authkey, serializer=SERIALIZER,
3275 shutdown_timeout=SHUTDOWN_TIMEOUT)
3276 manager2.connect()
3277 queue = manager2.get_queue()
3278
3279 self.assertEqual(queue.get(), self.result)
3280
3281 # Because we are using xmlrpclib for serialization instead of
3282 # pickle this will cause a serialization error.
3283 self.assertRaises(Exception, queue.put, time.sleep)
3284
3285 # Make queue finalizer run before the server is stopped
3286 del queue
3287
3288
3289 @hashlib_helper.requires_hashdigest('sha256')
3290 class _TestManagerRestart(BaseTestCase):
3291
3292 @classmethod
3293 def _putter(cls, address, authkey):
3294 manager = QueueManager(
3295 address=address, authkey=authkey, serializer=SERIALIZER,
3296 shutdown_timeout=SHUTDOWN_TIMEOUT)
3297 manager.connect()
3298 queue = manager.get_queue()
3299 queue.put('hello world')
3300
3301 @support.skip_if_sanitizer("TSan: leaks threads", thread=True)
3302 def test_rapid_restart(self):
3303 authkey = os.urandom(32)
3304 manager = QueueManager(
3305 address=(socket_helper.HOST, 0), authkey=authkey,
3306 serializer=SERIALIZER, shutdown_timeout=SHUTDOWN_TIMEOUT)
3307 try:
3308 srvr = manager.get_server()
3309 addr = srvr.address
3310 # Close the connection.Listener socket which gets opened as a part
3311 # of manager.get_server(). It's not needed for the test.
3312 srvr.listener.close()
3313 manager.start()
3314
3315 p = self.Process(target=self._putter, args=(manager.address, authkey))
3316 p.start()
3317 p.join()
3318 queue = manager.get_queue()
3319 self.assertEqual(queue.get(), 'hello world')
3320 del queue
3321 finally:
3322 if hasattr(manager, "shutdown"):
3323 manager.shutdown()
3324
3325 manager = QueueManager(
3326 address=addr, authkey=authkey, serializer=SERIALIZER,
3327 shutdown_timeout=SHUTDOWN_TIMEOUT)
3328 try:
3329 manager.start()
3330 self.addCleanup(manager.shutdown)
3331 except OSError as e:
3332 if e.errno != errno.EADDRINUSE:
3333 raise
3334 # Retry after some time, in case the old socket was lingering
3335 # (sporadic failure on buildbots)
3336 time.sleep(1.0)
3337 manager = QueueManager(
3338 address=addr, authkey=authkey, serializer=SERIALIZER,
3339 shutdown_timeout=SHUTDOWN_TIMEOUT)
3340 if hasattr(manager, "shutdown"):
3341 self.addCleanup(manager.shutdown)
3342
3343
3344 class FakeConnection:
3345 def send(self, payload):
3346 pass
3347
3348 def recv(self):
3349 return '#ERROR', pyqueue.Empty()
3350
3351 class TestManagerExceptions(unittest.TestCase):
3352 # Issue 106558: Manager exceptions avoids creating cyclic references.
3353 def setUp(self):
3354 self.mgr = multiprocessing.Manager()
3355
3356 def tearDown(self):
3357 self.mgr.shutdown()
3358 self.mgr.join()
3359
3360 def test_queue_get(self):
3361 queue = self.mgr.Queue()
3362 if gc.isenabled():
3363 gc.disable()
3364 self.addCleanup(gc.enable)
3365 try:
3366 queue.get_nowait()
3367 except pyqueue.Empty as e:
3368 wr = weakref.ref(e)
3369 self.assertEqual(wr(), None)
3370
3371 def test_dispatch(self):
3372 if gc.isenabled():
3373 gc.disable()
3374 self.addCleanup(gc.enable)
3375 try:
3376 multiprocessing.managers.dispatch(FakeConnection(), None, None)
3377 except pyqueue.Empty as e:
3378 wr = weakref.ref(e)
3379 self.assertEqual(wr(), None)
3380
3381 #
3382 #
3383 #
3384
3385 SENTINEL = latin('')
3386
3387 class _TestConnection(BaseTestCase):
3388
3389 ALLOWED_TYPES = ('processes', 'threads')
3390
3391 @classmethod
3392 def _echo(cls, conn):
3393 for msg in iter(conn.recv_bytes, SENTINEL):
3394 conn.send_bytes(msg)
3395 conn.close()
3396
3397 def test_connection(self):
3398 conn, child_conn = self.Pipe()
3399
3400 p = self.Process(target=self._echo, args=(child_conn,))
3401 p.daemon = True
3402 p.start()
3403
3404 seq = [1, 2.25, None]
3405 msg = latin('hello world')
3406 longmsg = msg * 10
3407 arr = array.array('i', list(range(4)))
3408
3409 if self.TYPE == 'processes':
3410 self.assertEqual(type(conn.fileno()), int)
3411
3412 self.assertEqual(conn.send(seq), None)
3413 self.assertEqual(conn.recv(), seq)
3414
3415 self.assertEqual(conn.send_bytes(msg), None)
3416 self.assertEqual(conn.recv_bytes(), msg)
3417
3418 if self.TYPE == 'processes':
3419 buffer = array.array('i', [0]*10)
3420 expected = list(arr) + [0] * (10 - len(arr))
3421 self.assertEqual(conn.send_bytes(arr), None)
3422 self.assertEqual(conn.recv_bytes_into(buffer),
3423 len(arr) * buffer.itemsize)
3424 self.assertEqual(list(buffer), expected)
3425
3426 buffer = array.array('i', [0]*10)
3427 expected = [0] * 3 + list(arr) + [0] * (10 - 3 - len(arr))
3428 self.assertEqual(conn.send_bytes(arr), None)
3429 self.assertEqual(conn.recv_bytes_into(buffer, 3 * buffer.itemsize),
3430 len(arr) * buffer.itemsize)
3431 self.assertEqual(list(buffer), expected)
3432
3433 buffer = bytearray(latin(' ' * 40))
3434 self.assertEqual(conn.send_bytes(longmsg), None)
3435 try:
3436 res = conn.recv_bytes_into(buffer)
3437 except multiprocessing.BufferTooShort as e:
3438 self.assertEqual(e.args, (longmsg,))
3439 else:
3440 self.fail('expected BufferTooShort, got %s' % res)
3441
3442 poll = TimingWrapper(conn.poll)
3443
3444 self.assertEqual(poll(), False)
3445 self.assertTimingAlmostEqual(poll.elapsed, 0)
3446
3447 self.assertEqual(poll(-1), False)
3448 self.assertTimingAlmostEqual(poll.elapsed, 0)
3449
3450 self.assertEqual(poll(TIMEOUT1), False)
3451 self.assertTimingAlmostEqual(poll.elapsed, TIMEOUT1)
3452
3453 conn.send(None)
3454 time.sleep(.1)
3455
3456 self.assertEqual(poll(TIMEOUT1), True)
3457 self.assertTimingAlmostEqual(poll.elapsed, 0)
3458
3459 self.assertEqual(conn.recv(), None)
3460
3461 really_big_msg = latin('X') * (1024 * 1024 * 16) # 16Mb
3462 conn.send_bytes(really_big_msg)
3463 self.assertEqual(conn.recv_bytes(), really_big_msg)
3464
3465 conn.send_bytes(SENTINEL) # tell child to quit
3466 child_conn.close()
3467
3468 if self.TYPE == 'processes':
3469 self.assertEqual(conn.readable, True)
3470 self.assertEqual(conn.writable, True)
3471 self.assertRaises(EOFError, conn.recv)
3472 self.assertRaises(EOFError, conn.recv_bytes)
3473
3474 p.join()
3475
3476 def test_duplex_false(self):
3477 reader, writer = self.Pipe(duplex=False)
3478 self.assertEqual(writer.send(1), None)
3479 self.assertEqual(reader.recv(), 1)
3480 if self.TYPE == 'processes':
3481 self.assertEqual(reader.readable, True)
3482 self.assertEqual(reader.writable, False)
3483 self.assertEqual(writer.readable, False)
3484 self.assertEqual(writer.writable, True)
3485 self.assertRaises(OSError, reader.send, 2)
3486 self.assertRaises(OSError, writer.recv)
3487 self.assertRaises(OSError, writer.poll)
3488
3489 def test_spawn_close(self):
3490 # We test that a pipe connection can be closed by parent
3491 # process immediately after child is spawned. On Windows this
3492 # would have sometimes failed on old versions because
3493 # child_conn would be closed before the child got a chance to
3494 # duplicate it.
3495 conn, child_conn = self.Pipe()
3496
3497 p = self.Process(target=self._echo, args=(child_conn,))
3498 p.daemon = True
3499 p.start()
3500 child_conn.close() # this might complete before child initializes
3501
3502 msg = latin('hello')
3503 conn.send_bytes(msg)
3504 self.assertEqual(conn.recv_bytes(), msg)
3505
3506 conn.send_bytes(SENTINEL)
3507 conn.close()
3508 p.join()
3509
3510 def test_sendbytes(self):
3511 if self.TYPE != 'processes':
3512 self.skipTest('test not appropriate for {}'.format(self.TYPE))
3513
3514 msg = latin('abcdefghijklmnopqrstuvwxyz')
3515 a, b = self.Pipe()
3516
3517 a.send_bytes(msg)
3518 self.assertEqual(b.recv_bytes(), msg)
3519
3520 a.send_bytes(msg, 5)
3521 self.assertEqual(b.recv_bytes(), msg[5:])
3522
3523 a.send_bytes(msg, 7, 8)
3524 self.assertEqual(b.recv_bytes(), msg[7:7+8])
3525
3526 a.send_bytes(msg, 26)
3527 self.assertEqual(b.recv_bytes(), latin(''))
3528
3529 a.send_bytes(msg, 26, 0)
3530 self.assertEqual(b.recv_bytes(), latin(''))
3531
3532 self.assertRaises(ValueError, a.send_bytes, msg, 27)
3533
3534 self.assertRaises(ValueError, a.send_bytes, msg, 22, 5)
3535
3536 self.assertRaises(ValueError, a.send_bytes, msg, 26, 1)
3537
3538 self.assertRaises(ValueError, a.send_bytes, msg, -1)
3539
3540 self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
3541
3542 @classmethod
3543 def _is_fd_assigned(cls, fd):
3544 try:
3545 os.fstat(fd)
3546 except OSError as e:
3547 if e.errno == errno.EBADF:
3548 return False
3549 raise
3550 else:
3551 return True
3552
3553 @classmethod
3554 def _writefd(cls, conn, data, create_dummy_fds=False):
3555 if create_dummy_fds:
3556 for i in range(0, 256):
3557 if not cls._is_fd_assigned(i):
3558 os.dup2(conn.fileno(), i)
3559 fd = reduction.recv_handle(conn)
3560 if msvcrt:
3561 fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
3562 os.write(fd, data)
3563 os.close(fd)
3564
3565 @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
3566 def test_fd_transfer(self):
3567 if self.TYPE != 'processes':
3568 self.skipTest("only makes sense with processes")
3569 conn, child_conn = self.Pipe(duplex=True)
3570
3571 p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
3572 p.daemon = True
3573 p.start()
3574 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
3575 with open(os_helper.TESTFN, "wb") as f:
3576 fd = f.fileno()
3577 if msvcrt:
3578 fd = msvcrt.get_osfhandle(fd)
3579 reduction.send_handle(conn, fd, p.pid)
3580 p.join()
3581 with open(os_helper.TESTFN, "rb") as f:
3582 self.assertEqual(f.read(), b"foo")
3583
3584 @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
3585 @unittest.skipIf(sys.platform == "win32",
3586 "test semantics don't make sense on Windows")
3587 @unittest.skipIf(MAXFD <= 256,
3588 "largest assignable fd number is too small")
3589 @unittest.skipUnless(hasattr(os, "dup2"),
3590 "test needs os.dup2()")
3591 def test_large_fd_transfer(self):
3592 # With fd > 256 (issue #11657)
3593 if self.TYPE != 'processes':
3594 self.skipTest("only makes sense with processes")
3595 conn, child_conn = self.Pipe(duplex=True)
3596
3597 p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
3598 p.daemon = True
3599 p.start()
3600 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
3601 with open(os_helper.TESTFN, "wb") as f:
3602 fd = f.fileno()
3603 for newfd in range(256, MAXFD):
3604 if not self._is_fd_assigned(newfd):
3605 break
3606 else:
3607 self.fail("could not find an unassigned large file descriptor")
3608 os.dup2(fd, newfd)
3609 try:
3610 reduction.send_handle(conn, newfd, p.pid)
3611 finally:
3612 os.close(newfd)
3613 p.join()
3614 with open(os_helper.TESTFN, "rb") as f:
3615 self.assertEqual(f.read(), b"bar")
3616
3617 @classmethod
3618 def _send_data_without_fd(self, conn):
3619 os.write(conn.fileno(), b"\0")
3620
3621 @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
3622 @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
3623 def test_missing_fd_transfer(self):
3624 # Check that exception is raised when received data is not
3625 # accompanied by a file descriptor in ancillary data.
3626 if self.TYPE != 'processes':
3627 self.skipTest("only makes sense with processes")
3628 conn, child_conn = self.Pipe(duplex=True)
3629
3630 p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
3631 p.daemon = True
3632 p.start()
3633 self.assertRaises(RuntimeError, reduction.recv_handle, conn)
3634 p.join()
3635
3636 def test_context(self):
3637 a, b = self.Pipe()
3638
3639 with a, b:
3640 a.send(1729)
3641 self.assertEqual(b.recv(), 1729)
3642 if self.TYPE == 'processes':
3643 self.assertFalse(a.closed)
3644 self.assertFalse(b.closed)
3645
3646 if self.TYPE == 'processes':
3647 self.assertTrue(a.closed)
3648 self.assertTrue(b.closed)
3649 self.assertRaises(OSError, a.recv)
3650 self.assertRaises(OSError, b.recv)
3651
3652 class _TestListener(BaseTestCase):
3653
3654 ALLOWED_TYPES = ('processes',)
3655
3656 def test_multiple_bind(self):
3657 for family in self.connection.families:
3658 l = self.connection.Listener(family=family)
3659 self.addCleanup(l.close)
3660 self.assertRaises(OSError, self.connection.Listener,
3661 l.address, family)
3662
3663 def test_context(self):
3664 with self.connection.Listener() as l:
3665 with self.connection.Client(l.address) as c:
3666 with l.accept() as d:
3667 c.send(1729)
3668 self.assertEqual(d.recv(), 1729)
3669
3670 if self.TYPE == 'processes':
3671 self.assertRaises(OSError, l.accept)
3672
3673 def test_empty_authkey(self):
3674 # bpo-43952: allow empty bytes as authkey
3675 def handler(*args):
3676 raise RuntimeError('Connection took too long...')
3677
3678 def run(addr, authkey):
3679 client = self.connection.Client(addr, authkey=authkey)
3680 client.send(1729)
3681
3682 key = b''
3683
3684 with self.connection.Listener(authkey=key) as listener:
3685 thread = threading.Thread(target=run, args=(listener.address, key))
3686 thread.start()
3687 try:
3688 with listener.accept() as d:
3689 self.assertEqual(d.recv(), 1729)
3690 finally:
3691 thread.join()
3692
3693 if self.TYPE == 'processes':
3694 with self.assertRaises(OSError):
3695 listener.accept()
3696
3697 @unittest.skipUnless(util.abstract_sockets_supported,
3698 "test needs abstract socket support")
3699 def test_abstract_socket(self):
3700 with self.connection.Listener("\0something") as listener:
3701 with self.connection.Client(listener.address) as client:
3702 with listener.accept() as d:
3703 client.send(1729)
3704 self.assertEqual(d.recv(), 1729)
3705
3706 if self.TYPE == 'processes':
3707 self.assertRaises(OSError, listener.accept)
3708
3709
3710 class _TestListenerClient(BaseTestCase):
3711
3712 ALLOWED_TYPES = ('processes', 'threads')
3713
3714 @classmethod
3715 def _test(cls, address):
3716 conn = cls.connection.Client(address)
3717 conn.send('hello')
3718 conn.close()
3719
3720 def test_listener_client(self):
3721 for family in self.connection.families:
3722 l = self.connection.Listener(family=family)
3723 p = self.Process(target=self._test, args=(l.address,))
3724 p.daemon = True
3725 p.start()
3726 conn = l.accept()
3727 self.assertEqual(conn.recv(), 'hello')
3728 p.join()
3729 l.close()
3730
3731 def test_issue14725(self):
3732 l = self.connection.Listener()
3733 p = self.Process(target=self._test, args=(l.address,))
3734 p.daemon = True
3735 p.start()
3736 time.sleep(1)
3737 # On Windows the client process should by now have connected,
3738 # written data and closed the pipe handle by now. This causes
3739 # ConnectNamdedPipe() to fail with ERROR_NO_DATA. See Issue
3740 # 14725.
3741 conn = l.accept()
3742 self.assertEqual(conn.recv(), 'hello')
3743 conn.close()
3744 p.join()
3745 l.close()
3746
3747 def test_issue16955(self):
3748 for fam in self.connection.families:
3749 l = self.connection.Listener(family=fam)
3750 c = self.connection.Client(l.address)
3751 a = l.accept()
3752 a.send_bytes(b"hello")
3753 self.assertTrue(c.poll(1))
3754 a.close()
3755 c.close()
3756 l.close()
3757
3758 class _TestPoll(BaseTestCase):
3759
3760 ALLOWED_TYPES = ('processes', 'threads')
3761
3762 def test_empty_string(self):
3763 a, b = self.Pipe()
3764 self.assertEqual(a.poll(), False)
3765 b.send_bytes(b'')
3766 self.assertEqual(a.poll(), True)
3767 self.assertEqual(a.poll(), True)
3768
3769 @classmethod
3770 def _child_strings(cls, conn, strings):
3771 for s in strings:
3772 time.sleep(0.1)
3773 conn.send_bytes(s)
3774 conn.close()
3775
3776 def test_strings(self):
3777 strings = (b'hello', b'', b'a', b'b', b'', b'bye', b'', b'lop')
3778 a, b = self.Pipe()
3779 p = self.Process(target=self._child_strings, args=(b, strings))
3780 p.start()
3781
3782 for s in strings:
3783 for i in range(200):
3784 if a.poll(0.01):
3785 break
3786 x = a.recv_bytes()
3787 self.assertEqual(s, x)
3788
3789 p.join()
3790
3791 @classmethod
3792 def _child_boundaries(cls, r):
3793 # Polling may "pull" a message in to the child process, but we
3794 # don't want it to pull only part of a message, as that would
3795 # corrupt the pipe for any other processes which might later
3796 # read from it.
3797 r.poll(5)
3798
3799 def test_boundaries(self):
3800 r, w = self.Pipe(False)
3801 p = self.Process(target=self._child_boundaries, args=(r,))
3802 p.start()
3803 time.sleep(2)
3804 L = [b"first", b"second"]
3805 for obj in L:
3806 w.send_bytes(obj)
3807 w.close()
3808 p.join()
3809 self.assertIn(r.recv_bytes(), L)
3810
3811 @classmethod
3812 def _child_dont_merge(cls, b):
3813 b.send_bytes(b'a')
3814 b.send_bytes(b'b')
3815 b.send_bytes(b'cd')
3816
3817 def test_dont_merge(self):
3818 a, b = self.Pipe()
3819 self.assertEqual(a.poll(0.0), False)
3820 self.assertEqual(a.poll(0.1), False)
3821
3822 p = self.Process(target=self._child_dont_merge, args=(b,))
3823 p.start()
3824
3825 self.assertEqual(a.recv_bytes(), b'a')
3826 self.assertEqual(a.poll(1.0), True)
3827 self.assertEqual(a.poll(1.0), True)
3828 self.assertEqual(a.recv_bytes(), b'b')
3829 self.assertEqual(a.poll(1.0), True)
3830 self.assertEqual(a.poll(1.0), True)
3831 self.assertEqual(a.poll(0.0), True)
3832 self.assertEqual(a.recv_bytes(), b'cd')
3833
3834 p.join()
3835
3836 #
3837 # Test of sending connection and socket objects between processes
3838 #
3839
3840 @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
3841 @hashlib_helper.requires_hashdigest('sha256')
3842 class _TestPicklingConnections(BaseTestCase):
3843
3844 ALLOWED_TYPES = ('processes',)
3845
3846 @classmethod
3847 def tearDownClass(cls):
3848 from multiprocessing import resource_sharer
3849 resource_sharer.stop(timeout=support.LONG_TIMEOUT)
3850
3851 @classmethod
3852 def _listener(cls, conn, families):
3853 for fam in families:
3854 l = cls.connection.Listener(family=fam)
3855 conn.send(l.address)
3856 new_conn = l.accept()
3857 conn.send(new_conn)
3858 new_conn.close()
3859 l.close()
3860
3861 l = socket.create_server((socket_helper.HOST, 0))
3862 conn.send(l.getsockname())
3863 new_conn, addr = l.accept()
3864 conn.send(new_conn)
3865 new_conn.close()
3866 l.close()
3867
3868 conn.recv()
3869
3870 @classmethod
3871 def _remote(cls, conn):
3872 for (address, msg) in iter(conn.recv, None):
3873 client = cls.connection.Client(address)
3874 client.send(msg.upper())
3875 client.close()
3876
3877 address, msg = conn.recv()
3878 client = socket.socket()
3879 client.connect(address)
3880 client.sendall(msg.upper())
3881 client.close()
3882
3883 conn.close()
3884
3885 def test_pickling(self):
3886 families = self.connection.families
3887
3888 lconn, lconn0 = self.Pipe()
3889 lp = self.Process(target=self._listener, args=(lconn0, families))
3890 lp.daemon = True
3891 lp.start()
3892 lconn0.close()
3893
3894 rconn, rconn0 = self.Pipe()
3895 rp = self.Process(target=self._remote, args=(rconn0,))
3896 rp.daemon = True
3897 rp.start()
3898 rconn0.close()
3899
3900 for fam in families:
3901 msg = ('This connection uses family %s' % fam).encode('ascii')
3902 address = lconn.recv()
3903 rconn.send((address, msg))
3904 new_conn = lconn.recv()
3905 self.assertEqual(new_conn.recv(), msg.upper())
3906
3907 rconn.send(None)
3908
3909 msg = latin('This connection uses a normal socket')
3910 address = lconn.recv()
3911 rconn.send((address, msg))
3912 new_conn = lconn.recv()
3913 buf = []
3914 while True:
3915 s = new_conn.recv(100)
3916 if not s:
3917 break
3918 buf.append(s)
3919 buf = b''.join(buf)
3920 self.assertEqual(buf, msg.upper())
3921 new_conn.close()
3922
3923 lconn.send(None)
3924
3925 rconn.close()
3926 lconn.close()
3927
3928 lp.join()
3929 rp.join()
3930
3931 @classmethod
3932 def child_access(cls, conn):
3933 w = conn.recv()
3934 w.send('all is well')
3935 w.close()
3936
3937 r = conn.recv()
3938 msg = r.recv()
3939 conn.send(msg*2)
3940
3941 conn.close()
3942
3943 def test_access(self):
3944 # On Windows, if we do not specify a destination pid when
3945 # using DupHandle then we need to be careful to use the
3946 # correct access flags for DuplicateHandle(), or else
3947 # DupHandle.detach() will raise PermissionError. For example,
3948 # for a read only pipe handle we should use
3949 # access=FILE_GENERIC_READ. (Unfortunately
3950 # DUPLICATE_SAME_ACCESS does not work.)
3951 conn, child_conn = self.Pipe()
3952 p = self.Process(target=self.child_access, args=(child_conn,))
3953 p.daemon = True
3954 p.start()
3955 child_conn.close()
3956
3957 r, w = self.Pipe(duplex=False)
3958 conn.send(w)
3959 w.close()
3960 self.assertEqual(r.recv(), 'all is well')
3961 r.close()
3962
3963 r, w = self.Pipe(duplex=False)
3964 conn.send(r)
3965 r.close()
3966 w.send('foobar')
3967 w.close()
3968 self.assertEqual(conn.recv(), 'foobar'*2)
3969
3970 p.join()
3971
3972 #
3973 #
3974 #
3975
3976 class _TestHeap(BaseTestCase):
3977
3978 ALLOWED_TYPES = ('processes',)
3979
3980 def setUp(self):
3981 super().setUp()
3982 # Make pristine heap for these tests
3983 self.old_heap = multiprocessing.heap.BufferWrapper._heap
3984 multiprocessing.heap.BufferWrapper._heap = multiprocessing.heap.Heap()
3985
3986 def tearDown(self):
3987 multiprocessing.heap.BufferWrapper._heap = self.old_heap
3988 super().tearDown()
3989
3990 def test_heap(self):
3991 iterations = 5000
3992 maxblocks = 50
3993 blocks = []
3994
3995 # get the heap object
3996 heap = multiprocessing.heap.BufferWrapper._heap
3997 heap._DISCARD_FREE_SPACE_LARGER_THAN = 0
3998
3999 # create and destroy lots of blocks of different sizes
4000 for i in range(iterations):
4001 size = int(random.lognormvariate(0, 1) * 1000)
4002 b = multiprocessing.heap.BufferWrapper(size)
4003 blocks.append(b)
4004 if len(blocks) > maxblocks:
4005 i = random.randrange(maxblocks)
4006 del blocks[i]
4007 del b
4008
4009 # verify the state of the heap
4010 with heap._lock:
4011 all = []
4012 free = 0
4013 occupied = 0
4014 for L in list(heap._len_to_seq.values()):
4015 # count all free blocks in arenas
4016 for arena, start, stop in L:
4017 all.append((heap._arenas.index(arena), start, stop,
4018 stop-start, 'free'))
4019 free += (stop-start)
4020 for arena, arena_blocks in heap._allocated_blocks.items():
4021 # count all allocated blocks in arenas
4022 for start, stop in arena_blocks:
4023 all.append((heap._arenas.index(arena), start, stop,
4024 stop-start, 'occupied'))
4025 occupied += (stop-start)
4026
4027 self.assertEqual(free + occupied,
4028 sum(arena.size for arena in heap._arenas))
4029
4030 all.sort()
4031
4032 for i in range(len(all)-1):
4033 (arena, start, stop) = all[i][:3]
4034 (narena, nstart, nstop) = all[i+1][:3]
4035 if arena != narena:
4036 # Two different arenas
4037 self.assertEqual(stop, heap._arenas[arena].size) # last block
4038 self.assertEqual(nstart, 0) # first block
4039 else:
4040 # Same arena: two adjacent blocks
4041 self.assertEqual(stop, nstart)
4042
4043 # test free'ing all blocks
4044 random.shuffle(blocks)
4045 while blocks:
4046 blocks.pop()
4047
4048 self.assertEqual(heap._n_frees, heap._n_mallocs)
4049 self.assertEqual(len(heap._pending_free_blocks), 0)
4050 self.assertEqual(len(heap._arenas), 0)
4051 self.assertEqual(len(heap._allocated_blocks), 0, heap._allocated_blocks)
4052 self.assertEqual(len(heap._len_to_seq), 0)
4053
4054 def test_free_from_gc(self):
4055 # Check that freeing of blocks by the garbage collector doesn't deadlock
4056 # (issue #12352).
4057 # Make sure the GC is enabled, and set lower collection thresholds to
4058 # make collections more frequent (and increase the probability of
4059 # deadlock).
4060 if not gc.isenabled():
4061 gc.enable()
4062 self.addCleanup(gc.disable)
4063 thresholds = gc.get_threshold()
4064 self.addCleanup(gc.set_threshold, *thresholds)
4065 gc.set_threshold(10)
4066
4067 # perform numerous block allocations, with cyclic references to make
4068 # sure objects are collected asynchronously by the gc
4069 for i in range(5000):
4070 a = multiprocessing.heap.BufferWrapper(1)
4071 b = multiprocessing.heap.BufferWrapper(1)
4072 # circular references
4073 a.buddy = b
4074 b.buddy = a
4075
4076 #
4077 #
4078 #
4079
4080 class _Foo(Structure):
4081 _fields_ = [
4082 ('x', c_int),
4083 ('y', c_double),
4084 ('z', c_longlong,)
4085 ]
4086
4087 class _TestSharedCTypes(BaseTestCase):
4088
4089 ALLOWED_TYPES = ('processes',)
4090
4091 def setUp(self):
4092 if not HAS_SHAREDCTYPES:
4093 self.skipTest("requires multiprocessing.sharedctypes")
4094
4095 @classmethod
4096 def _double(cls, x, y, z, foo, arr, string):
4097 x.value *= 2
4098 y.value *= 2
4099 z.value *= 2
4100 foo.x *= 2
4101 foo.y *= 2
4102 string.value *= 2
4103 for i in range(len(arr)):
4104 arr[i] *= 2
4105
4106 def test_sharedctypes(self, lock=False):
4107 x = Value('i', 7, lock=lock)
4108 y = Value(c_double, 1.0/3.0, lock=lock)
4109 z = Value(c_longlong, 2 ** 33, lock=lock)
4110 foo = Value(_Foo, 3, 2, lock=lock)
4111 arr = self.Array('d', list(range(10)), lock=lock)
4112 string = self.Array('c', 20, lock=lock)
4113 string.value = latin('hello')
4114
4115 p = self.Process(target=self._double, args=(x, y, z, foo, arr, string))
4116 p.daemon = True
4117 p.start()
4118 p.join()
4119
4120 self.assertEqual(x.value, 14)
4121 self.assertAlmostEqual(y.value, 2.0/3.0)
4122 self.assertEqual(z.value, 2 ** 34)
4123 self.assertEqual(foo.x, 6)
4124 self.assertAlmostEqual(foo.y, 4.0)
4125 for i in range(10):
4126 self.assertAlmostEqual(arr[i], i*2)
4127 self.assertEqual(string.value, latin('hellohello'))
4128
4129 def test_synchronize(self):
4130 self.test_sharedctypes(lock=True)
4131
4132 def test_copy(self):
4133 foo = _Foo(2, 5.0, 2 ** 33)
4134 bar = copy(foo)
4135 foo.x = 0
4136 foo.y = 0
4137 foo.z = 0
4138 self.assertEqual(bar.x, 2)
4139 self.assertAlmostEqual(bar.y, 5.0)
4140 self.assertEqual(bar.z, 2 ** 33)
4141
4142
4143 def resource_tracker_format_subtests(func):
4144 """Run given test using both resource tracker communication formats"""
4145 def _inner(self, *args, **kwargs):
4146 tracker = resource_tracker._resource_tracker
4147 for use_simple_format in False, True:
4148 with (
4149 self.subTest(use_simple_format=use_simple_format),
4150 unittest.mock.patch.object(
4151 tracker, '_use_simple_format', use_simple_format)
4152 ):
4153 func(self, *args, **kwargs)
4154 return _inner
4155
4156 @unittest.skipUnless(HAS_SHMEM, "requires multiprocessing.shared_memory")
4157 @hashlib_helper.requires_hashdigest('sha256')
4158 class _TestSharedMemory(BaseTestCase):
4159
4160 ALLOWED_TYPES = ('processes',)
4161
4162 @staticmethod
4163 def _attach_existing_shmem_then_write(shmem_name_or_obj, binary_data):
4164 if isinstance(shmem_name_or_obj, str):
4165 local_sms = shared_memory.SharedMemory(shmem_name_or_obj)
4166 else:
4167 local_sms = shmem_name_or_obj
4168 local_sms.buf[:len(binary_data)] = binary_data
4169 local_sms.close()
4170
4171 def _new_shm_name(self, prefix):
4172 # Add a PID to the name of a POSIX shared memory object to allow
4173 # running multiprocessing tests (test_multiprocessing_fork,
4174 # test_multiprocessing_spawn, etc) in parallel.
4175 return prefix + str(os.getpid())
4176
4177 def test_shared_memory_name_with_embedded_null(self):
4178 name_tsmb = self._new_shm_name('test01_null')
4179 sms = shared_memory.SharedMemory(name_tsmb, create=True, size=512)
4180 self.addCleanup(sms.unlink)
4181 with self.assertRaises(ValueError):
4182 shared_memory.SharedMemory(name_tsmb + '\0a', create=False, size=512)
4183 if shared_memory._USE_POSIX:
4184 orig_name = sms._name
4185 try:
4186 sms._name = orig_name + '\0a'
4187 with self.assertRaises(ValueError):
4188 sms.unlink()
4189 finally:
4190 sms._name = orig_name
4191
4192 def test_shared_memory_basics(self):
4193 name_tsmb = self._new_shm_name('test01_tsmb')
4194 sms = shared_memory.SharedMemory(name_tsmb, create=True, size=512)
4195 self.addCleanup(sms.unlink)
4196
4197 # Verify attributes are readable.
4198 self.assertEqual(sms.name, name_tsmb)
4199 self.assertGreaterEqual(sms.size, 512)
4200 self.assertGreaterEqual(len(sms.buf), sms.size)
4201
4202 # Verify __repr__
4203 self.assertIn(sms.name, str(sms))
4204 self.assertIn(str(sms.size), str(sms))
4205
4206 # Modify contents of shared memory segment through memoryview.
4207 sms.buf[0] = 42
4208 self.assertEqual(sms.buf[0], 42)
4209
4210 # Attach to existing shared memory segment.
4211 also_sms = shared_memory.SharedMemory(name_tsmb)
4212 self.assertEqual(also_sms.buf[0], 42)
4213 also_sms.close()
4214
4215 # Attach to existing shared memory segment but specify a new size.
4216 same_sms = shared_memory.SharedMemory(name_tsmb, size=20*sms.size)
4217 self.assertLess(same_sms.size, 20*sms.size) # Size was ignored.
4218 same_sms.close()
4219
4220 # Creating Shared Memory Segment with -ve size
4221 with self.assertRaises(ValueError):
4222 shared_memory.SharedMemory(create=True, size=-2)
4223
4224 # Attaching Shared Memory Segment without a name
4225 with self.assertRaises(ValueError):
4226 shared_memory.SharedMemory(create=False)
4227
4228 # Test if shared memory segment is created properly,
4229 # when _make_filename returns an existing shared memory segment name
4230 with unittest.mock.patch(
4231 'multiprocessing.shared_memory._make_filename') as mock_make_filename:
4232
4233 NAME_PREFIX = shared_memory._SHM_NAME_PREFIX
4234 names = [self._new_shm_name('test01_fn'), self._new_shm_name('test02_fn')]
4235 # Prepend NAME_PREFIX which can be '/psm_' or 'wnsm_', necessary
4236 # because some POSIX compliant systems require name to start with /
4237 names = [NAME_PREFIX + name for name in names]
4238
4239 mock_make_filename.side_effect = names
4240 shm1 = shared_memory.SharedMemory(create=True, size=1)
4241 self.addCleanup(shm1.unlink)
4242 self.assertEqual(shm1._name, names[0])
4243
4244 mock_make_filename.side_effect = names
4245 shm2 = shared_memory.SharedMemory(create=True, size=1)
4246 self.addCleanup(shm2.unlink)
4247 self.assertEqual(shm2._name, names[1])
4248
4249 if shared_memory._USE_POSIX:
4250 # Posix Shared Memory can only be unlinked once. Here we
4251 # test an implementation detail that is not observed across
4252 # all supported platforms (since WindowsNamedSharedMemory
4253 # manages unlinking on its own and unlink() does nothing).
4254 # True release of shared memory segment does not necessarily
4255 # happen until process exits, depending on the OS platform.
4256 name_dblunlink = self._new_shm_name('test01_dblunlink')
4257 sms_uno = shared_memory.SharedMemory(
4258 name_dblunlink,
4259 create=True,
4260 size=5000
4261 )
4262 with self.assertRaises(FileNotFoundError):
4263 try:
4264 self.assertGreaterEqual(sms_uno.size, 5000)
4265
4266 sms_duo = shared_memory.SharedMemory(name_dblunlink)
4267 sms_duo.unlink() # First shm_unlink() call.
4268 sms_duo.close()
4269 sms_uno.close()
4270
4271 finally:
4272 sms_uno.unlink() # A second shm_unlink() call is bad.
4273
4274 with self.assertRaises(FileExistsError):
4275 # Attempting to create a new shared memory segment with a
4276 # name that is already in use triggers an exception.
4277 there_can_only_be_one_sms = shared_memory.SharedMemory(
4278 name_tsmb,
4279 create=True,
4280 size=512
4281 )
4282
4283 if shared_memory._USE_POSIX:
4284 # Requesting creation of a shared memory segment with the option
4285 # to attach to an existing segment, if that name is currently in
4286 # use, should not trigger an exception.
4287 # Note: Using a smaller size could possibly cause truncation of
4288 # the existing segment but is OS platform dependent. In the
4289 # case of MacOS/darwin, requesting a smaller size is disallowed.
4290 class OptionalAttachSharedMemory(shared_memory.SharedMemory):
4291 _flags = os.O_CREAT | os.O_RDWR
4292 ok_if_exists_sms = OptionalAttachSharedMemory(name_tsmb)
4293 self.assertEqual(ok_if_exists_sms.size, sms.size)
4294 ok_if_exists_sms.close()
4295
4296 # Attempting to attach to an existing shared memory segment when
4297 # no segment exists with the supplied name triggers an exception.
4298 with self.assertRaises(FileNotFoundError):
4299 nonexisting_sms = shared_memory.SharedMemory('test01_notthere')
4300 nonexisting_sms.unlink() # Error should occur on prior line.
4301
4302 sms.close()
4303
4304 def test_shared_memory_recreate(self):
4305 # Test if shared memory segment is created properly,
4306 # when _make_filename returns an existing shared memory segment name
4307 with unittest.mock.patch(
4308 'multiprocessing.shared_memory._make_filename') as mock_make_filename:
4309
4310 NAME_PREFIX = shared_memory._SHM_NAME_PREFIX
4311 names = [self._new_shm_name('test03_fn'), self._new_shm_name('test04_fn')]
4312 # Prepend NAME_PREFIX which can be '/psm_' or 'wnsm_', necessary
4313 # because some POSIX compliant systems require name to start with /
4314 names = [NAME_PREFIX + name for name in names]
4315
4316 mock_make_filename.side_effect = names
4317 shm1 = shared_memory.SharedMemory(create=True, size=1)
4318 self.addCleanup(shm1.unlink)
4319 self.assertEqual(shm1._name, names[0])
4320
4321 mock_make_filename.side_effect = names
4322 shm2 = shared_memory.SharedMemory(create=True, size=1)
4323 self.addCleanup(shm2.unlink)
4324 self.assertEqual(shm2._name, names[1])
4325
4326 def test_invalid_shared_memory_creation(self):
4327 # Test creating a shared memory segment with negative size
4328 with self.assertRaises(ValueError):
4329 sms_invalid = shared_memory.SharedMemory(create=True, size=-1)
4330
4331 # Test creating a shared memory segment with size 0
4332 with self.assertRaises(ValueError):
4333 sms_invalid = shared_memory.SharedMemory(create=True, size=0)
4334
4335 # Test creating a shared memory segment without size argument
4336 with self.assertRaises(ValueError):
4337 sms_invalid = shared_memory.SharedMemory(create=True)
4338
4339 def test_shared_memory_pickle_unpickle(self):
4340 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4341 with self.subTest(proto=proto):
4342 sms = shared_memory.SharedMemory(create=True, size=512)
4343 self.addCleanup(sms.unlink)
4344 sms.buf[0:6] = b'pickle'
4345
4346 # Test pickling
4347 pickled_sms = pickle.dumps(sms, protocol=proto)
4348
4349 # Test unpickling
4350 sms2 = pickle.loads(pickled_sms)
4351 self.assertIsInstance(sms2, shared_memory.SharedMemory)
4352 self.assertEqual(sms.name, sms2.name)
4353 self.assertEqual(bytes(sms.buf[0:6]), b'pickle')
4354 self.assertEqual(bytes(sms2.buf[0:6]), b'pickle')
4355
4356 # Test that unpickled version is still the same SharedMemory
4357 sms.buf[0:6] = b'newval'
4358 self.assertEqual(bytes(sms.buf[0:6]), b'newval')
4359 self.assertEqual(bytes(sms2.buf[0:6]), b'newval')
4360
4361 sms2.buf[0:6] = b'oldval'
4362 self.assertEqual(bytes(sms.buf[0:6]), b'oldval')
4363 self.assertEqual(bytes(sms2.buf[0:6]), b'oldval')
4364
4365 def test_shared_memory_pickle_unpickle_dead_object(self):
4366 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4367 with self.subTest(proto=proto):
4368 sms = shared_memory.SharedMemory(create=True, size=512)
4369 sms.buf[0:6] = b'pickle'
4370 pickled_sms = pickle.dumps(sms, protocol=proto)
4371
4372 # Now, we are going to kill the original object.
4373 # So, unpickled one won't be able to attach to it.
4374 sms.close()
4375 sms.unlink()
4376
4377 with self.assertRaises(FileNotFoundError):
4378 pickle.loads(pickled_sms)
4379
4380 def test_shared_memory_across_processes(self):
4381 # bpo-40135: don't define shared memory block's name in case of
4382 # the failure when we run multiprocessing tests in parallel.
4383 sms = shared_memory.SharedMemory(create=True, size=512)
4384 self.addCleanup(sms.unlink)
4385
4386 # Verify remote attachment to existing block by name is working.
4387 p = self.Process(
4388 target=self._attach_existing_shmem_then_write,
4389 args=(sms.name, b'howdy')
4390 )
4391 p.daemon = True
4392 p.start()
4393 p.join()
4394 self.assertEqual(bytes(sms.buf[:5]), b'howdy')
4395
4396 # Verify pickling of SharedMemory instance also works.
4397 p = self.Process(
4398 target=self._attach_existing_shmem_then_write,
4399 args=(sms, b'HELLO')
4400 )
4401 p.daemon = True
4402 p.start()
4403 p.join()
4404 self.assertEqual(bytes(sms.buf[:5]), b'HELLO')
4405
4406 sms.close()
4407
4408 @unittest.skipIf(os.name != "posix", "not feasible in non-posix platforms")
4409 def test_shared_memory_SharedMemoryServer_ignores_sigint(self):
4410 # bpo-36368: protect SharedMemoryManager server process from
4411 # KeyboardInterrupt signals.
4412 smm = multiprocessing.managers.SharedMemoryManager()
4413 smm.start()
4414
4415 # make sure the manager works properly at the beginning
4416 sl = smm.ShareableList(range(10))
4417
4418 # the manager's server should ignore KeyboardInterrupt signals, and
4419 # maintain its connection with the current process, and success when
4420 # asked to deliver memory segments.
4421 os.kill(smm._process.pid, signal.SIGINT)
4422
4423 sl2 = smm.ShareableList(range(10))
4424
4425 # test that the custom signal handler registered in the Manager does
4426 # not affect signal handling in the parent process.
4427 with self.assertRaises(KeyboardInterrupt):
4428 os.kill(os.getpid(), signal.SIGINT)
4429
4430 smm.shutdown()
4431
4432 @unittest.skipIf(os.name != "posix", "resource_tracker is posix only")
4433 @resource_tracker_format_subtests
4434 def test_shared_memory_SharedMemoryManager_reuses_resource_tracker(self):
4435 # bpo-36867: test that a SharedMemoryManager uses the
4436 # same resource_tracker process as its parent.
4437 cmd = '''if 1:
4438 from multiprocessing.managers import SharedMemoryManager
4439
4440
4441 smm = SharedMemoryManager()
4442 smm.start()
4443 sl = smm.ShareableList(range(10))
4444 smm.shutdown()
4445 '''
4446 rc, out, err = test.support.script_helper.assert_python_ok('-c', cmd)
4447
4448 # Before bpo-36867 was fixed, a SharedMemoryManager not using the same
4449 # resource_tracker process as its parent would make the parent's
4450 # tracker complain about sl being leaked even though smm.shutdown()
4451 # properly released sl.
4452 self.assertFalse(err)
4453
4454 def test_shared_memory_SharedMemoryManager_basics(self):
4455 smm1 = multiprocessing.managers.SharedMemoryManager()
4456 with self.assertRaises(ValueError):
4457 smm1.SharedMemory(size=9) # Fails if SharedMemoryServer not started
4458 smm1.start()
4459 lol = [ smm1.ShareableList(range(i)) for i in range(5, 10) ]
4460 lom = [ smm1.SharedMemory(size=j) for j in range(32, 128, 16) ]
4461 doppleganger_list0 = shared_memory.ShareableList(name=lol[0].shm.name)
4462 self.assertEqual(len(doppleganger_list0), 5)
4463 doppleganger_shm0 = shared_memory.SharedMemory(name=lom[0].name)
4464 self.assertGreaterEqual(len(doppleganger_shm0.buf), 32)
4465 held_name = lom[0].name
4466 smm1.shutdown()
4467 if sys.platform != "win32":
4468 # Calls to unlink() have no effect on Windows platform; shared
4469 # memory will only be released once final process exits.
4470 with self.assertRaises(FileNotFoundError):
4471 # No longer there to be attached to again.
4472 absent_shm = shared_memory.SharedMemory(name=held_name)
4473
4474 with multiprocessing.managers.SharedMemoryManager() as smm2:
4475 sl = smm2.ShareableList("howdy")
4476 shm = smm2.SharedMemory(size=128)
4477 held_name = sl.shm.name
4478 if sys.platform != "win32":
4479 with self.assertRaises(FileNotFoundError):
4480 # No longer there to be attached to again.
4481 absent_sl = shared_memory.ShareableList(name=held_name)
4482
4483
4484 def test_shared_memory_ShareableList_basics(self):
4485 sl = shared_memory.ShareableList(
4486 ['howdy', b'HoWdY', -273.154, 100, None, True, 42]
4487 )
4488 self.addCleanup(sl.shm.unlink)
4489
4490 # Verify __repr__
4491 self.assertIn(sl.shm.name, str(sl))
4492 self.assertIn(str(list(sl)), str(sl))
4493
4494 # Index Out of Range (get)
4495 with self.assertRaises(IndexError):
4496 sl[7]
4497
4498 # Index Out of Range (set)
4499 with self.assertRaises(IndexError):
4500 sl[7] = 2
4501
4502 # Assign value without format change (str -> str)
4503 current_format = sl._get_packing_format(0)
4504 sl[0] = 'howdy'
4505 self.assertEqual(current_format, sl._get_packing_format(0))
4506
4507 # Verify attributes are readable.
4508 self.assertEqual(sl.format, '8s8sdqxxxxxx?xxxxxxxx?q')
4509
4510 # Exercise len().
4511 self.assertEqual(len(sl), 7)
4512
4513 # Exercise index().
4514 with warnings.catch_warnings():
4515 # Suppress BytesWarning when comparing against b'HoWdY'.
4516 warnings.simplefilter('ignore')
4517 with self.assertRaises(ValueError):
4518 sl.index('100')
4519 self.assertEqual(sl.index(100), 3)
4520
4521 # Exercise retrieving individual values.
4522 self.assertEqual(sl[0], 'howdy')
4523 self.assertEqual(sl[-2], True)
4524
4525 # Exercise iterability.
4526 self.assertEqual(
4527 tuple(sl),
4528 ('howdy', b'HoWdY', -273.154, 100, None, True, 42)
4529 )
4530
4531 # Exercise modifying individual values.
4532 sl[3] = 42
4533 self.assertEqual(sl[3], 42)
4534 sl[4] = 'some' # Change type at a given position.
4535 self.assertEqual(sl[4], 'some')
4536 self.assertEqual(sl.format, '8s8sdq8sxxxxxxx?q')
4537 with self.assertRaisesRegex(ValueError,
4538 "exceeds available storage"):
4539 sl[4] = 'far too many'
4540 self.assertEqual(sl[4], 'some')
4541 sl[0] = 'encodés' # Exactly 8 bytes of UTF-8 data
4542 self.assertEqual(sl[0], 'encodés')
4543 self.assertEqual(sl[1], b'HoWdY') # no spillage
4544 with self.assertRaisesRegex(ValueError,
4545 "exceeds available storage"):
4546 sl[0] = 'encodées' # Exactly 9 bytes of UTF-8 data
4547 self.assertEqual(sl[1], b'HoWdY')
4548 with self.assertRaisesRegex(ValueError,
4549 "exceeds available storage"):
4550 sl[1] = b'123456789'
4551 self.assertEqual(sl[1], b'HoWdY')
4552
4553 # Exercise count().
4554 with warnings.catch_warnings():
4555 # Suppress BytesWarning when comparing against b'HoWdY'.
4556 warnings.simplefilter('ignore')
4557 self.assertEqual(sl.count(42), 2)
4558 self.assertEqual(sl.count(b'HoWdY'), 1)
4559 self.assertEqual(sl.count(b'adios'), 0)
4560
4561 # Exercise creating a duplicate.
4562 name_duplicate = self._new_shm_name('test03_duplicate')
4563 sl_copy = shared_memory.ShareableList(sl, name=name_duplicate)
4564 try:
4565 self.assertNotEqual(sl.shm.name, sl_copy.shm.name)
4566 self.assertEqual(name_duplicate, sl_copy.shm.name)
4567 self.assertEqual(list(sl), list(sl_copy))
4568 self.assertEqual(sl.format, sl_copy.format)
4569 sl_copy[-1] = 77
4570 self.assertEqual(sl_copy[-1], 77)
4571 self.assertNotEqual(sl[-1], 77)
4572 sl_copy.shm.close()
4573 finally:
4574 sl_copy.shm.unlink()
4575
4576 # Obtain a second handle on the same ShareableList.
4577 sl_tethered = shared_memory.ShareableList(name=sl.shm.name)
4578 self.assertEqual(sl.shm.name, sl_tethered.shm.name)
4579 sl_tethered[-1] = 880
4580 self.assertEqual(sl[-1], 880)
4581 sl_tethered.shm.close()
4582
4583 sl.shm.close()
4584
4585 # Exercise creating an empty ShareableList.
4586 empty_sl = shared_memory.ShareableList()
4587 try:
4588 self.assertEqual(len(empty_sl), 0)
4589 self.assertEqual(empty_sl.format, '')
4590 self.assertEqual(empty_sl.count('any'), 0)
4591 with self.assertRaises(ValueError):
4592 empty_sl.index(None)
4593 empty_sl.shm.close()
4594 finally:
4595 empty_sl.shm.unlink()
4596
4597 def test_shared_memory_ShareableList_pickling(self):
4598 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4599 with self.subTest(proto=proto):
4600 sl = shared_memory.ShareableList(range(10))
4601 self.addCleanup(sl.shm.unlink)
4602
4603 serialized_sl = pickle.dumps(sl, protocol=proto)
4604 deserialized_sl = pickle.loads(serialized_sl)
4605 self.assertIsInstance(
4606 deserialized_sl, shared_memory.ShareableList)
4607 self.assertEqual(deserialized_sl[-1], 9)
4608 self.assertIsNot(sl, deserialized_sl)
4609
4610 deserialized_sl[4] = "changed"
4611 self.assertEqual(sl[4], "changed")
4612 sl[3] = "newvalue"
4613 self.assertEqual(deserialized_sl[3], "newvalue")
4614
4615 larger_sl = shared_memory.ShareableList(range(400))
4616 self.addCleanup(larger_sl.shm.unlink)
4617 serialized_larger_sl = pickle.dumps(larger_sl, protocol=proto)
4618 self.assertEqual(len(serialized_sl), len(serialized_larger_sl))
4619 larger_sl.shm.close()
4620
4621 deserialized_sl.shm.close()
4622 sl.shm.close()
4623
4624 def test_shared_memory_ShareableList_pickling_dead_object(self):
4625 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
4626 with self.subTest(proto=proto):
4627 sl = shared_memory.ShareableList(range(10))
4628 serialized_sl = pickle.dumps(sl, protocol=proto)
4629
4630 # Now, we are going to kill the original object.
4631 # So, unpickled one won't be able to attach to it.
4632 sl.shm.close()
4633 sl.shm.unlink()
4634
4635 with self.assertRaises(FileNotFoundError):
4636 pickle.loads(serialized_sl)
4637
4638 def test_shared_memory_cleaned_after_process_termination(self):
4639 cmd = '''if 1:
4640 import os, time, sys
4641 from multiprocessing import shared_memory
4642
4643 # Create a shared_memory segment, and send the segment name
4644 sm = shared_memory.SharedMemory(create=True, size=10)
4645 sys.stdout.write(sm.name + '\\n')
4646 sys.stdout.flush()
4647 time.sleep(100)
4648 '''
4649 with subprocess.Popen([sys.executable, '-E', '-c', cmd],
4650 stdout=subprocess.PIPE,
4651 stderr=subprocess.PIPE) as p:
4652 name = p.stdout.readline().strip().decode()
4653
4654 # killing abruptly processes holding reference to a shared memory
4655 # segment should not leak the given memory segment.
4656 p.terminate()
4657 p.wait()
4658
4659 err_msg = ("A SharedMemory segment was leaked after "
4660 "a process was abruptly terminated")
4661 for _ in support.sleeping_retry(support.LONG_TIMEOUT, err_msg):
4662 try:
4663 smm = shared_memory.SharedMemory(name, create=False)
4664 except FileNotFoundError:
4665 break
4666
4667 if os.name == 'posix':
4668 # Without this line it was raising warnings like:
4669 # UserWarning: resource_tracker:
4670 # There appear to be 1 leaked shared_memory
4671 # objects to clean up at shutdown
4672 # See: https://bugs.python.org/issue45209
4673 resource_tracker.unregister(f"/{name}", "shared_memory")
4674
4675 # A warning was emitted by the subprocess' own
4676 # resource_tracker (on Windows, shared memory segments
4677 # are released automatically by the OS).
4678 err = p.stderr.read().decode()
4679 self.assertIn(
4680 "resource_tracker: There appear to be 1 leaked "
4681 "shared_memory objects to clean up at shutdown", err)
4682
4683 @unittest.skipIf(os.name != "posix", "resource_tracker is posix only")
4684 @resource_tracker_format_subtests
4685 def test_shared_memory_untracking(self):
4686 # gh-82300: When a separate Python process accesses shared memory
4687 # with track=False, it must not cause the memory to be deleted
4688 # when terminating.
4689 cmd = '''if 1:
4690 import sys
4691 from multiprocessing.shared_memory import SharedMemory
4692 mem = SharedMemory(create=False, name=sys.argv[1], track=False)
4693 mem.close()
4694 '''
4695 mem = shared_memory.SharedMemory(create=True, size=10)
4696 # The resource tracker shares pipes with the subprocess, and so
4697 # err existing means that the tracker process has terminated now.
4698 try:
4699 rc, out, err = script_helper.assert_python_ok("-c", cmd, mem.name)
4700 self.assertNotIn(b"resource_tracker", err)
4701 self.assertEqual(rc, 0)
4702 mem2 = shared_memory.SharedMemory(create=False, name=mem.name)
4703 mem2.close()
4704 finally:
4705 try:
4706 mem.unlink()
4707 except OSError:
4708 pass
4709 mem.close()
4710
4711 @unittest.skipIf(os.name != "posix", "resource_tracker is posix only")
4712 @resource_tracker_format_subtests
4713 def test_shared_memory_tracking(self):
4714 # gh-82300: When a separate Python process accesses shared memory
4715 # with track=True, it must cause the memory to be deleted when
4716 # terminating.
4717 cmd = '''if 1:
4718 import sys
4719 from multiprocessing.shared_memory import SharedMemory
4720 mem = SharedMemory(create=False, name=sys.argv[1], track=True)
4721 mem.close()
4722 '''
4723 mem = shared_memory.SharedMemory(create=True, size=10)
4724 try:
4725 rc, out, err = script_helper.assert_python_ok("-c", cmd, mem.name)
4726 self.assertEqual(rc, 0)
4727 self.assertIn(
4728 b"resource_tracker: There appear to be 1 leaked "
4729 b"shared_memory objects to clean up at shutdown", err)
4730 finally:
4731 try:
4732 mem.unlink()
4733 except OSError:
4734 pass
4735 resource_tracker.unregister(mem._name, "shared_memory")
4736 mem.close()
4737
4738 #
4739 # Test to verify that `Finalize` works.
4740 #
4741
4742 class _TestFinalize(BaseTestCase):
4743
4744 ALLOWED_TYPES = ('processes',)
4745
4746 def setUp(self):
4747 self.registry_backup = util._finalizer_registry.copy()
4748 util._finalizer_registry.clear()
4749
4750 def tearDown(self):
4751 gc.collect() # For PyPy or other GCs.
4752 self.assertFalse(util._finalizer_registry)
4753 util._finalizer_registry.update(self.registry_backup)
4754
4755 @classmethod
4756 def _test_finalize(cls, conn):
4757 class Foo(object):
4758 pass
4759
4760 a = Foo()
4761 util.Finalize(a, conn.send, args=('a',))
4762 del a # triggers callback for a
4763 gc.collect() # For PyPy or other GCs.
4764
4765 b = Foo()
4766 close_b = util.Finalize(b, conn.send, args=('b',))
4767 close_b() # triggers callback for b
4768 close_b() # does nothing because callback has already been called
4769 del b # does nothing because callback has already been called
4770 gc.collect() # For PyPy or other GCs.
4771
4772 c = Foo()
4773 util.Finalize(c, conn.send, args=('c',))
4774
4775 d10 = Foo()
4776 util.Finalize(d10, conn.send, args=('d10',), exitpriority=1)
4777
4778 d01 = Foo()
4779 util.Finalize(d01, conn.send, args=('d01',), exitpriority=0)
4780 d02 = Foo()
4781 util.Finalize(d02, conn.send, args=('d02',), exitpriority=0)
4782 d03 = Foo()
4783 util.Finalize(d03, conn.send, args=('d03',), exitpriority=0)
4784
4785 util.Finalize(None, conn.send, args=('e',), exitpriority=-10)
4786
4787 util.Finalize(None, conn.send, args=('STOP',), exitpriority=-100)
4788
4789 # call multiprocessing's cleanup function then exit process without
4790 # garbage collecting locals
4791 util._exit_function()
4792 conn.close()
4793 os._exit(0)
4794
4795 def test_finalize(self):
4796 conn, child_conn = self.Pipe()
4797
4798 p = self.Process(target=self._test_finalize, args=(child_conn,))
4799 p.daemon = True
4800 p.start()
4801 p.join()
4802
4803 result = [obj for obj in iter(conn.recv, 'STOP')]
4804 self.assertEqual(result, ['a', 'b', 'd10', 'd03', 'd02', 'd01', 'e'])
4805
4806 @support.requires_resource('cpu')
4807 def test_thread_safety(self):
4808 # bpo-24484: _run_finalizers() should be thread-safe
4809 def cb():
4810 pass
4811
4812 class Foo(object):
4813 def __init__(self):
4814 self.ref = self # create reference cycle
4815 # insert finalizer at random key
4816 util.Finalize(self, cb, exitpriority=random.randint(1, 100))
4817
4818 finish = False
4819 exc = None
4820
4821 def run_finalizers():
4822 nonlocal exc
4823 while not finish:
4824 time.sleep(random.random() * 1e-1)
4825 try:
4826 # A GC run will eventually happen during this,
4827 # collecting stale Foo's and mutating the registry
4828 util._run_finalizers()
4829 except Exception as e:
4830 exc = e
4831
4832 def make_finalizers():
4833 nonlocal exc
4834 d = {}
4835 while not finish:
4836 try:
4837 # Old Foo's get gradually replaced and later
4838 # collected by the GC (because of the cyclic ref)
4839 d[random.getrandbits(5)] = {Foo() for i in range(10)}
4840 except Exception as e:
4841 exc = e
4842 d.clear()
4843
4844 old_interval = sys.getswitchinterval()
4845 old_threshold = gc.get_threshold()
4846 try:
4847 support.setswitchinterval(1e-6)
4848 gc.set_threshold(5, 5, 5)
4849 threads = [threading.Thread(target=run_finalizers),
4850 threading.Thread(target=make_finalizers)]
4851 with threading_helper.start_threads(threads):
4852 time.sleep(4.0) # Wait a bit to trigger race condition
4853 finish = True
4854 if exc is not None:
4855 raise exc
4856 finally:
4857 sys.setswitchinterval(old_interval)
4858 gc.set_threshold(*old_threshold)
4859 gc.collect() # Collect remaining Foo's
4860
4861
4862 #
4863 # Test that from ... import * works for each module
4864 #
4865
4866 class _TestImportStar(unittest.TestCase):
4867
4868 def get_module_names(self):
4869 import glob
4870 folder = os.path.dirname(multiprocessing.__file__)
4871 pattern = os.path.join(glob.escape(folder), '*.py')
4872 files = glob.glob(pattern)
4873 modules = [os.path.splitext(os.path.split(f)[1])[0] for f in files]
4874 modules = ['multiprocessing.' + m for m in modules]
4875 modules.remove('multiprocessing.__init__')
4876 modules.append('multiprocessing')
4877 return modules
4878
4879 def test_import(self):
4880 modules = self.get_module_names()
4881 if sys.platform == 'win32':
4882 modules.remove('multiprocessing.popen_fork')
4883 modules.remove('multiprocessing.popen_forkserver')
4884 modules.remove('multiprocessing.popen_spawn_posix')
4885 else:
4886 modules.remove('multiprocessing.popen_spawn_win32')
4887 if not HAS_REDUCTION:
4888 modules.remove('multiprocessing.popen_forkserver')
4889
4890 if c_int is None:
4891 # This module requires _ctypes
4892 modules.remove('multiprocessing.sharedctypes')
4893
4894 for name in modules:
4895 __import__(name)
4896 mod = sys.modules[name]
4897 self.assertTrue(hasattr(mod, '__all__'), name)
4898
4899 for attr in mod.__all__:
4900 self.assertTrue(
4901 hasattr(mod, attr),
4902 '%r does not have attribute %r' % (mod, attr)
4903 )
4904
4905 #
4906 # Quick test that logging works -- does not test logging output
4907 #
4908
4909 class _TestLogging(BaseTestCase):
4910
4911 ALLOWED_TYPES = ('processes',)
4912
4913 def test_enable_logging(self):
4914 logger = multiprocessing.get_logger()
4915 logger.setLevel(util.SUBWARNING)
4916 self.assertTrue(logger is not None)
4917 logger.debug('this will not be printed')
4918 logger.info('nor will this')
4919 logger.setLevel(LOG_LEVEL)
4920
4921 @classmethod
4922 def _test_level(cls, conn):
4923 logger = multiprocessing.get_logger()
4924 conn.send(logger.getEffectiveLevel())
4925
4926 def test_level(self):
4927 LEVEL1 = 32
4928 LEVEL2 = 37
4929
4930 logger = multiprocessing.get_logger()
4931 root_logger = logging.getLogger()
4932 root_level = root_logger.level
4933
4934 reader, writer = multiprocessing.Pipe(duplex=False)
4935
4936 logger.setLevel(LEVEL1)
4937 p = self.Process(target=self._test_level, args=(writer,))
4938 p.start()
4939 self.assertEqual(LEVEL1, reader.recv())
4940 p.join()
4941 p.close()
4942
4943 logger.setLevel(logging.NOTSET)
4944 root_logger.setLevel(LEVEL2)
4945 p = self.Process(target=self._test_level, args=(writer,))
4946 p.start()
4947 self.assertEqual(LEVEL2, reader.recv())
4948 p.join()
4949 p.close()
4950
4951 root_logger.setLevel(root_level)
4952 logger.setLevel(level=LOG_LEVEL)
4953
4954 def test_filename(self):
4955 logger = multiprocessing.get_logger()
4956 original_level = logger.level
4957 try:
4958 logger.setLevel(util.DEBUG)
4959 stream = io.StringIO()
4960 handler = logging.StreamHandler(stream)
4961 logging_format = '[%(levelname)s] [%(filename)s] %(message)s'
4962 handler.setFormatter(logging.Formatter(logging_format))
4963 logger.addHandler(handler)
4964 logger.info('1')
4965 util.info('2')
4966 logger.debug('3')
4967 filename = os.path.basename(__file__)
4968 log_record = stream.getvalue()
4969 self.assertIn(f'[INFO] [{filename}] 1', log_record)
4970 self.assertIn(f'[INFO] [{filename}] 2', log_record)
4971 self.assertIn(f'[DEBUG] [{filename}] 3', log_record)
4972 finally:
4973 logger.setLevel(original_level)
4974 logger.removeHandler(handler)
4975 handler.close()
4976
4977
4978 # class _TestLoggingProcessName(BaseTestCase):
4979 #
4980 # def handle(self, record):
4981 # assert record.processName == multiprocessing.current_process().name
4982 # self.__handled = True
4983 #
4984 # def test_logging(self):
4985 # handler = logging.Handler()
4986 # handler.handle = self.handle
4987 # self.__handled = False
4988 # # Bypass getLogger() and side-effects
4989 # logger = logging.getLoggerClass()(
4990 # 'multiprocessing.test.TestLoggingProcessName')
4991 # logger.addHandler(handler)
4992 # logger.propagate = False
4993 #
4994 # logger.warn('foo')
4995 # assert self.__handled
4996
4997 #
4998 # Check that Process.join() retries if os.waitpid() fails with EINTR
4999 #
5000
5001 class _TestPollEintr(BaseTestCase):
5002
5003 ALLOWED_TYPES = ('processes',)
5004
5005 @classmethod
5006 def _killer(cls, pid):
5007 time.sleep(0.1)
5008 os.kill(pid, signal.SIGUSR1)
5009
5010 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
5011 def test_poll_eintr(self):
5012 got_signal = [False]
5013 def record(*args):
5014 got_signal[0] = True
5015 pid = os.getpid()
5016 oldhandler = signal.signal(signal.SIGUSR1, record)
5017 try:
5018 killer = self.Process(target=self._killer, args=(pid,))
5019 killer.start()
5020 try:
5021 p = self.Process(target=time.sleep, args=(2,))
5022 p.start()
5023 p.join()
5024 finally:
5025 killer.join()
5026 self.assertTrue(got_signal[0])
5027 self.assertEqual(p.exitcode, 0)
5028 finally:
5029 signal.signal(signal.SIGUSR1, oldhandler)
5030
5031 #
5032 # Test to verify handle verification, see issue 3321
5033 #
5034
5035 class TestInvalidHandle(unittest.TestCase):
5036
5037 @unittest.skipIf(WIN32, "skipped on Windows")
5038 def test_invalid_handles(self):
5039 conn = multiprocessing.connection.Connection(44977608)
5040 # check that poll() doesn't crash
5041 try:
5042 conn.poll()
5043 except (ValueError, OSError):
5044 pass
5045 finally:
5046 # Hack private attribute _handle to avoid printing an error
5047 # in conn.__del__
5048 conn._handle = None
5049 self.assertRaises((ValueError, OSError),
5050 multiprocessing.connection.Connection, -1)
5051
5052
5053
5054 @hashlib_helper.requires_hashdigest('sha256')
5055 class OtherTest(unittest.TestCase):
5056 # TODO: add more tests for deliver/answer challenge.
5057 def test_deliver_challenge_auth_failure(self):
5058 class _FakeConnection(object):
5059 def recv_bytes(self, size):
5060 return b'something bogus'
5061 def send_bytes(self, data):
5062 pass
5063 self.assertRaises(multiprocessing.AuthenticationError,
5064 multiprocessing.connection.deliver_challenge,
5065 _FakeConnection(), b'abc')
5066
5067 def test_answer_challenge_auth_failure(self):
5068 class _FakeConnection(object):
5069 def __init__(self):
5070 self.count = 0
5071 def recv_bytes(self, size):
5072 self.count += 1
5073 if self.count == 1:
5074 return multiprocessing.connection._CHALLENGE
5075 elif self.count == 2:
5076 return b'something bogus'
5077 return b''
5078 def send_bytes(self, data):
5079 pass
5080 self.assertRaises(multiprocessing.AuthenticationError,
5081 multiprocessing.connection.answer_challenge,
5082 _FakeConnection(), b'abc')
5083
5084
5085 @hashlib_helper.requires_hashdigest('md5')
5086 @hashlib_helper.requires_hashdigest('sha256')
5087 class ChallengeResponseTest(unittest.TestCase):
5088 authkey = b'supadupasecretkey'
5089
5090 def create_response(self, message):
5091 return multiprocessing.connection._create_response(
5092 self.authkey, message
5093 )
5094
5095 def verify_challenge(self, message, response):
5096 return multiprocessing.connection._verify_challenge(
5097 self.authkey, message, response
5098 )
5099
5100 def test_challengeresponse(self):
5101 for algo in [None, "md5", "sha256"]:
5102 with self.subTest(f"{algo=}"):
5103 msg = b'is-twenty-bytes-long' # The length of a legacy message.
5104 if algo:
5105 prefix = b'{%s}' % algo.encode("ascii")
5106 else:
5107 prefix = b''
5108 msg = prefix + msg
5109 response = self.create_response(msg)
5110 if not response.startswith(prefix):
5111 self.fail(response)
5112 self.verify_challenge(msg, response)
5113
5114 # TODO(gpshead): We need integration tests for handshakes between modern
5115 # deliver_challenge() and verify_response() code and connections running a
5116 # test-local copy of the legacy Python <=3.11 implementations.
5117
5118 # TODO(gpshead): properly annotate tests for requires_hashdigest rather than
5119 # only running these on a platform supporting everything. otherwise logic
5120 # issues preventing it from working on FIPS mode setups will be hidden.
5121
5122 #
5123 # Test Manager.start()/Pool.__init__() initializer feature - see issue 5585
5124 #
5125
5126 def initializer(ns):
5127 ns.test += 1
5128
5129 @hashlib_helper.requires_hashdigest('sha256')
5130 class TestInitializers(unittest.TestCase):
5131 def setUp(self):
5132 self.mgr = multiprocessing.Manager()
5133 self.ns = self.mgr.Namespace()
5134 self.ns.test = 0
5135
5136 def tearDown(self):
5137 self.mgr.shutdown()
5138 self.mgr.join()
5139
5140 def test_manager_initializer(self):
5141 m = multiprocessing.managers.SyncManager()
5142 self.assertRaises(TypeError, m.start, 1)
5143 m.start(initializer, (self.ns,))
5144 self.assertEqual(self.ns.test, 1)
5145 m.shutdown()
5146 m.join()
5147
5148 def test_pool_initializer(self):
5149 self.assertRaises(TypeError, multiprocessing.Pool, initializer=1)
5150 p = multiprocessing.Pool(1, initializer, (self.ns,))
5151 p.close()
5152 p.join()
5153 self.assertEqual(self.ns.test, 1)
5154
5155 #
5156 # Issue 5155, 5313, 5331: Test process in processes
5157 # Verifies os.close(sys.stdin.fileno) vs. sys.stdin.close() behavior
5158 #
5159
5160 def _this_sub_process(q):
5161 try:
5162 item = q.get(block=False)
5163 except pyqueue.Empty:
5164 pass
5165
5166 def _test_process():
5167 queue = multiprocessing.Queue()
5168 subProc = multiprocessing.Process(target=_this_sub_process, args=(queue,))
5169 subProc.daemon = True
5170 subProc.start()
5171 subProc.join()
5172
5173 def _afunc(x):
5174 return x*x
5175
5176 def pool_in_process():
5177 pool = multiprocessing.Pool(processes=4)
5178 x = pool.map(_afunc, [1, 2, 3, 4, 5, 6, 7])
5179 pool.close()
5180 pool.join()
5181
5182 class _file_like(object):
5183 def __init__(self, delegate):
5184 self._delegate = delegate
5185 self._pid = None
5186
5187 @property
5188 def cache(self):
5189 pid = os.getpid()
5190 # There are no race conditions since fork keeps only the running thread
5191 if pid != self._pid:
5192 self._pid = pid
5193 self._cache = []
5194 return self._cache
5195
5196 def write(self, data):
5197 self.cache.append(data)
5198
5199 def flush(self):
5200 self._delegate.write(''.join(self.cache))
5201 self._cache = []
5202
5203 class TestStdinBadfiledescriptor(unittest.TestCase):
5204
5205 def test_queue_in_process(self):
5206 proc = multiprocessing.Process(target=_test_process)
5207 proc.start()
5208 proc.join()
5209
5210 def test_pool_in_process(self):
5211 p = multiprocessing.Process(target=pool_in_process)
5212 p.start()
5213 p.join()
5214
5215 def test_flushing(self):
5216 sio = io.StringIO()
5217 flike = _file_like(sio)
5218 flike.write('foo')
5219 proc = multiprocessing.Process(target=lambda: flike.flush())
5220 flike.flush()
5221 assert sio.getvalue() == 'foo'
5222
5223
5224 class TestWait(unittest.TestCase):
5225
5226 @classmethod
5227 def _child_test_wait(cls, w, slow):
5228 for i in range(10):
5229 if slow:
5230 time.sleep(random.random() * 0.100)
5231 w.send((i, os.getpid()))
5232 w.close()
5233
5234 def test_wait(self, slow=False):
5235 from multiprocessing.connection import wait
5236 readers = []
5237 procs = []
5238 messages = []
5239
5240 for i in range(4):
5241 r, w = multiprocessing.Pipe(duplex=False)
5242 p = multiprocessing.Process(target=self._child_test_wait, args=(w, slow))
5243 p.daemon = True
5244 p.start()
5245 w.close()
5246 readers.append(r)
5247 procs.append(p)
5248 self.addCleanup(p.join)
5249
5250 while readers:
5251 for r in wait(readers):
5252 try:
5253 msg = r.recv()
5254 except EOFError:
5255 readers.remove(r)
5256 r.close()
5257 else:
5258 messages.append(msg)
5259
5260 messages.sort()
5261 expected = sorted((i, p.pid) for i in range(10) for p in procs)
5262 self.assertEqual(messages, expected)
5263
5264 @classmethod
5265 def _child_test_wait_socket(cls, address, slow):
5266 s = socket.socket()
5267 s.connect(address)
5268 for i in range(10):
5269 if slow:
5270 time.sleep(random.random() * 0.100)
5271 s.sendall(('%s\n' % i).encode('ascii'))
5272 s.close()
5273
5274 def test_wait_socket(self, slow=False):
5275 from multiprocessing.connection import wait
5276 l = socket.create_server((socket_helper.HOST, 0))
5277 addr = l.getsockname()
5278 readers = []
5279 procs = []
5280 dic = {}
5281
5282 for i in range(4):
5283 p = multiprocessing.Process(target=self._child_test_wait_socket,
5284 args=(addr, slow))
5285 p.daemon = True
5286 p.start()
5287 procs.append(p)
5288 self.addCleanup(p.join)
5289
5290 for i in range(4):
5291 r, _ = l.accept()
5292 readers.append(r)
5293 dic[r] = []
5294 l.close()
5295
5296 while readers:
5297 for r in wait(readers):
5298 msg = r.recv(32)
5299 if not msg:
5300 readers.remove(r)
5301 r.close()
5302 else:
5303 dic[r].append(msg)
5304
5305 expected = ''.join('%s\n' % i for i in range(10)).encode('ascii')
5306 for v in dic.values():
5307 self.assertEqual(b''.join(v), expected)
5308
5309 def test_wait_slow(self):
5310 self.test_wait(True)
5311
5312 def test_wait_socket_slow(self):
5313 self.test_wait_socket(True)
5314
5315 @support.requires_resource('walltime')
5316 def test_wait_timeout(self):
5317 from multiprocessing.connection import wait
5318
5319 timeout = 5.0 # seconds
5320 a, b = multiprocessing.Pipe()
5321
5322 start = time.monotonic()
5323 res = wait([a, b], timeout)
5324 delta = time.monotonic() - start
5325
5326 self.assertEqual(res, [])
5327 self.assertGreater(delta, timeout - CLOCK_RES)
5328
5329 b.send(None)
5330 res = wait([a, b], 20)
5331 self.assertEqual(res, [a])
5332
5333 @classmethod
5334 def signal_and_sleep(cls, sem, period):
5335 sem.release()
5336 time.sleep(period)
5337
5338 @support.requires_resource('walltime')
5339 def test_wait_integer(self):
5340 from multiprocessing.connection import wait
5341
5342 expected = 3
5343 sorted_ = lambda l: sorted(l, key=lambda x: id(x))
5344 sem = multiprocessing.Semaphore(0)
5345 a, b = multiprocessing.Pipe()
5346 p = multiprocessing.Process(target=self.signal_and_sleep,
5347 args=(sem, expected))
5348
5349 p.start()
5350 self.assertIsInstance(p.sentinel, int)
5351 self.assertTrue(sem.acquire(timeout=20))
5352
5353 start = time.monotonic()
5354 res = wait([a, p.sentinel, b], expected + 20)
5355 delta = time.monotonic() - start
5356
5357 self.assertEqual(res, [p.sentinel])
5358 self.assertLess(delta, expected + 2)
5359 self.assertGreater(delta, expected - 2)
5360
5361 a.send(None)
5362
5363 start = time.monotonic()
5364 res = wait([a, p.sentinel, b], 20)
5365 delta = time.monotonic() - start
5366
5367 self.assertEqual(sorted_(res), sorted_([p.sentinel, b]))
5368 self.assertLess(delta, 0.4)
5369
5370 b.send(None)
5371
5372 start = time.monotonic()
5373 res = wait([a, p.sentinel, b], 20)
5374 delta = time.monotonic() - start
5375
5376 self.assertEqual(sorted_(res), sorted_([a, p.sentinel, b]))
5377 self.assertLess(delta, 0.4)
5378
5379 p.terminate()
5380 p.join()
5381
5382 def test_neg_timeout(self):
5383 from multiprocessing.connection import wait
5384 a, b = multiprocessing.Pipe()
5385 t = time.monotonic()
5386 res = wait([a], timeout=-1)
5387 t = time.monotonic() - t
5388 self.assertEqual(res, [])
5389 self.assertLess(t, 1)
5390 a.close()
5391 b.close()
5392
5393 #
5394 # Issue 14151: Test invalid family on invalid environment
5395 #
5396
5397 class TestInvalidFamily(unittest.TestCase):
5398
5399 @unittest.skipIf(WIN32, "skipped on Windows")
5400 def test_invalid_family(self):
5401 with self.assertRaises(ValueError):
5402 multiprocessing.connection.Listener(r'\\.\test')
5403
5404 @unittest.skipUnless(WIN32, "skipped on non-Windows platforms")
5405 def test_invalid_family_win32(self):
5406 with self.assertRaises(ValueError):
5407 multiprocessing.connection.Listener('/var/test.pipe')
5408
5409 #
5410 # Issue 12098: check sys.flags of child matches that for parent
5411 #
5412
5413 class TestFlags(unittest.TestCase):
5414 @classmethod
5415 def run_in_grandchild(cls, conn):
5416 conn.send(tuple(sys.flags))
5417
5418 @classmethod
5419 def run_in_child(cls, start_method):
5420 import json
5421 mp = multiprocessing.get_context(start_method)
5422 r, w = mp.Pipe(duplex=False)
5423 p = mp.Process(target=cls.run_in_grandchild, args=(w,))
5424 with warnings.catch_warnings(category=DeprecationWarning):
5425 p.start()
5426 grandchild_flags = r.recv()
5427 p.join()
5428 r.close()
5429 w.close()
5430 flags = (tuple(sys.flags), grandchild_flags)
5431 print(json.dumps(flags))
5432
5433 def test_flags(self):
5434 import json
5435 # start child process using unusual flags
5436 prog = (
5437 'from test._test_multiprocessing import TestFlags; '
5438 f'TestFlags.run_in_child({multiprocessing.get_start_method()!r})'
5439 )
5440 data = subprocess.check_output(
5441 [sys.executable, '-E', '-S', '-O', '-c', prog])
5442 child_flags, grandchild_flags = json.loads(data.decode('ascii'))
5443 self.assertEqual(child_flags, grandchild_flags)
5444
5445 #
5446 # Test interaction with socket timeouts - see Issue #6056
5447 #
5448
5449 class TestTimeouts(unittest.TestCase):
5450 @classmethod
5451 def _test_timeout(cls, child, address):
5452 time.sleep(1)
5453 child.send(123)
5454 child.close()
5455 conn = multiprocessing.connection.Client(address)
5456 conn.send(456)
5457 conn.close()
5458
5459 def test_timeout(self):
5460 old_timeout = socket.getdefaulttimeout()
5461 try:
5462 socket.setdefaulttimeout(0.1)
5463 parent, child = multiprocessing.Pipe(duplex=True)
5464 l = multiprocessing.connection.Listener(family='AF_INET')
5465 p = multiprocessing.Process(target=self._test_timeout,
5466 args=(child, l.address))
5467 p.start()
5468 child.close()
5469 self.assertEqual(parent.recv(), 123)
5470 parent.close()
5471 conn = l.accept()
5472 self.assertEqual(conn.recv(), 456)
5473 conn.close()
5474 l.close()
5475 join_process(p)
5476 finally:
5477 socket.setdefaulttimeout(old_timeout)
5478
5479 #
5480 # Test what happens with no "if __name__ == '__main__'"
5481 #
5482
5483 class TestNoForkBomb(unittest.TestCase):
5484 def test_noforkbomb(self):
5485 sm = multiprocessing.get_start_method()
5486 name = os.path.join(os.path.dirname(__file__), 'mp_fork_bomb.py')
5487 if sm != 'fork':
5488 rc, out, err = test.support.script_helper.assert_python_failure(name, sm)
5489 self.assertEqual(out, b'')
5490 self.assertIn(b'RuntimeError', err)
5491 else:
5492 rc, out, err = test.support.script_helper.assert_python_ok(name, sm)
5493 self.assertEqual(out.rstrip(), b'123')
5494 self.assertEqual(err, b'')
5495
5496 #
5497 # Issue #17555: ForkAwareThreadLock
5498 #
5499
5500 class TestForkAwareThreadLock(unittest.TestCase):
5501 # We recursively start processes. Issue #17555 meant that the
5502 # after fork registry would get duplicate entries for the same
5503 # lock. The size of the registry at generation n was ~2**n.
5504
5505 @classmethod
5506 def child(cls, n, conn):
5507 if n > 1:
5508 p = multiprocessing.Process(target=cls.child, args=(n-1, conn))
5509 p.start()
5510 conn.close()
5511 join_process(p)
5512 else:
5513 conn.send(len(util._afterfork_registry))
5514 conn.close()
5515
5516 def test_lock(self):
5517 r, w = multiprocessing.Pipe(False)
5518 l = util.ForkAwareThreadLock()
5519 old_size = len(util._afterfork_registry)
5520 p = multiprocessing.Process(target=self.child, args=(5, w))
5521 p.start()
5522 w.close()
5523 new_size = r.recv()
5524 join_process(p)
5525 self.assertLessEqual(new_size, old_size)
5526
5527 #
5528 # Check that non-forked child processes do not inherit unneeded fds/handles
5529 #
5530
5531 class TestCloseFds(unittest.TestCase):
5532
5533 def get_high_socket_fd(self):
5534 if WIN32:
5535 # The child process will not have any socket handles, so
5536 # calling socket.fromfd() should produce WSAENOTSOCK even
5537 # if there is a handle of the same number.
5538 return socket.socket().detach()
5539 else:
5540 # We want to produce a socket with an fd high enough that a
5541 # freshly created child process will not have any fds as high.
5542 fd = socket.socket().detach()
5543 to_close = []
5544 while fd < 50:
5545 to_close.append(fd)
5546 fd = os.dup(fd)
5547 for x in to_close:
5548 os.close(x)
5549 return fd
5550
5551 def close(self, fd):
5552 if WIN32:
5553 socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd).close()
5554 else:
5555 os.close(fd)
5556
5557 @classmethod
5558 def _test_closefds(cls, conn, fd):
5559 try:
5560 s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
5561 except Exception as e:
5562 conn.send(e)
5563 else:
5564 s.close()
5565 conn.send(None)
5566
5567 def test_closefd(self):
5568 if not HAS_REDUCTION:
5569 raise unittest.SkipTest('requires fd pickling')
5570
5571 reader, writer = multiprocessing.Pipe()
5572 fd = self.get_high_socket_fd()
5573 try:
5574 p = multiprocessing.Process(target=self._test_closefds,
5575 args=(writer, fd))
5576 p.start()
5577 writer.close()
5578 e = reader.recv()
5579 join_process(p)
5580 finally:
5581 self.close(fd)
5582 writer.close()
5583 reader.close()
5584
5585 if multiprocessing.get_start_method() == 'fork':
5586 self.assertIs(e, None)
5587 else:
5588 WSAENOTSOCK = 10038
5589 self.assertIsInstance(e, OSError)
5590 self.assertTrue(e.errno == errno.EBADF or
5591 e.winerror == WSAENOTSOCK, e)
5592
5593 #
5594 # Issue #17097: EINTR should be ignored by recv(), send(), accept() etc
5595 #
5596
5597 class TestIgnoreEINTR(unittest.TestCase):
5598
5599 # Sending CONN_MAX_SIZE bytes into a multiprocessing pipe must block
5600 CONN_MAX_SIZE = max(support.PIPE_MAX_SIZE, support.SOCK_MAX_SIZE)
5601
5602 @classmethod
5603 def _test_ignore(cls, conn):
5604 def handler(signum, frame):
5605 pass
5606 signal.signal(signal.SIGUSR1, handler)
5607 conn.send('ready')
5608 x = conn.recv()
5609 conn.send(x)
5610 conn.send_bytes(b'x' * cls.CONN_MAX_SIZE)
5611
5612 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
5613 def test_ignore(self):
5614 conn, child_conn = multiprocessing.Pipe()
5615 try:
5616 p = multiprocessing.Process(target=self._test_ignore,
5617 args=(child_conn,))
5618 p.daemon = True
5619 p.start()
5620 child_conn.close()
5621 self.assertEqual(conn.recv(), 'ready')
5622 time.sleep(0.1)
5623 os.kill(p.pid, signal.SIGUSR1)
5624 time.sleep(0.1)
5625 conn.send(1234)
5626 self.assertEqual(conn.recv(), 1234)
5627 time.sleep(0.1)
5628 os.kill(p.pid, signal.SIGUSR1)
5629 self.assertEqual(conn.recv_bytes(), b'x' * self.CONN_MAX_SIZE)
5630 time.sleep(0.1)
5631 p.join()
5632 finally:
5633 conn.close()
5634
5635 @classmethod
5636 def _test_ignore_listener(cls, conn):
5637 def handler(signum, frame):
5638 pass
5639 signal.signal(signal.SIGUSR1, handler)
5640 with multiprocessing.connection.Listener() as l:
5641 conn.send(l.address)
5642 a = l.accept()
5643 a.send('welcome')
5644
5645 @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1')
5646 def test_ignore_listener(self):
5647 conn, child_conn = multiprocessing.Pipe()
5648 try:
5649 p = multiprocessing.Process(target=self._test_ignore_listener,
5650 args=(child_conn,))
5651 p.daemon = True
5652 p.start()
5653 child_conn.close()
5654 address = conn.recv()
5655 time.sleep(0.1)
5656 os.kill(p.pid, signal.SIGUSR1)
5657 time.sleep(0.1)
5658 client = multiprocessing.connection.Client(address)
5659 self.assertEqual(client.recv(), 'welcome')
5660 p.join()
5661 finally:
5662 conn.close()
5663
5664 class TestStartMethod(unittest.TestCase):
5665 @classmethod
5666 def _check_context(cls, conn):
5667 conn.send(multiprocessing.get_start_method())
5668
5669 def check_context(self, ctx):
5670 r, w = ctx.Pipe(duplex=False)
5671 p = ctx.Process(target=self._check_context, args=(w,))
5672 p.start()
5673 w.close()
5674 child_method = r.recv()
5675 r.close()
5676 p.join()
5677 self.assertEqual(child_method, ctx.get_start_method())
5678
5679 def test_context(self):
5680 for method in ('fork', 'spawn', 'forkserver'):
5681 try:
5682 ctx = multiprocessing.get_context(method)
5683 except ValueError:
5684 continue
5685 self.assertEqual(ctx.get_start_method(), method)
5686 self.assertIs(ctx.get_context(), ctx)
5687 self.assertRaises(ValueError, ctx.set_start_method, 'spawn')
5688 self.assertRaises(ValueError, ctx.set_start_method, None)
5689 self.check_context(ctx)
5690
5691 @staticmethod
5692 def _dummy_func():
5693 pass
5694
5695 def test_spawn_dont_set_context(self):
5696 # Run a process with spawn or forkserver context may change
5697 # the global start method, see gh-109263.
5698 for method in ('fork', 'spawn', 'forkserver'):
5699 multiprocessing.set_start_method(None, force=True)
5700
5701 try:
5702 ctx = multiprocessing.get_context(method)
5703 except ValueError:
5704 continue
5705 process = ctx.Process(target=self._dummy_func)
5706 process.start()
5707 process.join()
5708 self.assertIsNone(multiprocessing.get_start_method(allow_none=True))
5709
5710 def test_context_check_module_types(self):
5711 try:
5712 ctx = multiprocessing.get_context('forkserver')
5713 except ValueError:
5714 raise unittest.SkipTest('forkserver should be available')
5715 with self.assertRaisesRegex(TypeError, 'module_names must be a list of strings'):
5716 ctx.set_forkserver_preload([1, 2, 3])
5717
5718 def test_set_get(self):
5719 multiprocessing.set_forkserver_preload(PRELOAD)
5720 count = 0
5721 old_method = multiprocessing.get_start_method()
5722 try:
5723 for method in ('fork', 'spawn', 'forkserver'):
5724 try:
5725 multiprocessing.set_start_method(method, force=True)
5726 except ValueError:
5727 continue
5728 self.assertEqual(multiprocessing.get_start_method(), method)
5729 ctx = multiprocessing.get_context()
5730 self.assertEqual(ctx.get_start_method(), method)
5731 self.assertTrue(type(ctx).__name__.lower().startswith(method))
5732 self.assertTrue(
5733 ctx.Process.__name__.lower().startswith(method))
5734 self.check_context(multiprocessing)
5735 count += 1
5736 finally:
5737 multiprocessing.set_start_method(old_method, force=True)
5738 self.assertGreaterEqual(count, 1)
5739
5740 def test_get_all(self):
5741 methods = multiprocessing.get_all_start_methods()
5742 if sys.platform == 'win32':
5743 self.assertEqual(methods, ['spawn'])
5744 else:
5745 self.assertTrue(methods == ['fork', 'spawn'] or
5746 methods == ['spawn', 'fork'] or
5747 methods == ['fork', 'spawn', 'forkserver'] or
5748 methods == ['spawn', 'fork', 'forkserver'])
5749
5750 def test_preload_resources(self):
5751 if multiprocessing.get_start_method() != 'forkserver':
5752 self.skipTest("test only relevant for 'forkserver' method")
5753 name = os.path.join(os.path.dirname(__file__), 'mp_preload.py')
5754 rc, out, err = test.support.script_helper.assert_python_ok(name)
5755 out = out.decode()
5756 err = err.decode()
5757 if out.rstrip() != 'ok' or err != '':
5758 print(out)
5759 print(err)
5760 self.fail("failed spawning forkserver or grandchild")
5761
5762 @unittest.skipIf(sys.platform == "win32",
5763 "Only Spawn on windows so no risk of mixing")
5764 @only_run_in_spawn_testsuite("avoids redundant testing.")
5765 def test_mixed_startmethod(self):
5766 # Fork-based locks cannot be used with spawned process
5767 for process_method in ["spawn", "forkserver"]:
5768 queue = multiprocessing.get_context("fork").Queue()
5769 process_ctx = multiprocessing.get_context(process_method)
5770 p = process_ctx.Process(target=close_queue, args=(queue,))
5771 err_msg = "A SemLock created in a fork"
5772 with self.assertRaisesRegex(RuntimeError, err_msg):
5773 p.start()
5774
5775 # non-fork-based locks can be used with all other start methods
5776 for queue_method in ["spawn", "forkserver"]:
5777 for process_method in multiprocessing.get_all_start_methods():
5778 queue = multiprocessing.get_context(queue_method).Queue()
5779 process_ctx = multiprocessing.get_context(process_method)
5780 p = process_ctx.Process(target=close_queue, args=(queue,))
5781 p.start()
5782 p.join()
5783
5784 @classmethod
5785 def _put_one_in_queue(cls, queue):
5786 queue.put(1)
5787
5788 @classmethod
5789 def _put_two_and_nest_once(cls, queue):
5790 queue.put(2)
5791 process = multiprocessing.Process(target=cls._put_one_in_queue, args=(queue,))
5792 process.start()
5793 process.join()
5794
5795 def test_nested_startmethod(self):
5796 # gh-108520: Regression test to ensure that child process can send its
5797 # arguments to another process
5798 queue = multiprocessing.Queue()
5799
5800 process = multiprocessing.Process(target=self._put_two_and_nest_once, args=(queue,))
5801 process.start()
5802 process.join()
5803
5804 results = []
5805 while not queue.empty():
5806 results.append(queue.get())
5807
5808 # gh-109706: queue.put(1) can write into the queue before queue.put(2),
5809 # there is no synchronization in the test.
5810 self.assertSetEqual(set(results), set([2, 1]))
5811
5812
5813 @unittest.skipIf(sys.platform == "win32",
5814 "test semantics don't make sense on Windows")
5815 class TestResourceTracker(unittest.TestCase):
5816
5817 def test_resource_tracker(self):
5818 #
5819 # Check that killing process does not leak named semaphores
5820 #
5821 cmd = '''if 1:
5822 import time, os
5823 import multiprocessing as mp
5824 from multiprocessing import resource_tracker
5825 from multiprocessing.shared_memory import SharedMemory
5826
5827 mp.set_start_method("spawn")
5828
5829
5830 def create_and_register_resource(rtype):
5831 if rtype == "semaphore":
5832 lock = mp.Lock()
5833 return lock, lock._semlock.name
5834 elif rtype == "shared_memory":
5835 sm = SharedMemory(create=True, size=10)
5836 return sm, sm._name
5837 else:
5838 raise ValueError(
5839 "Resource type {{}} not understood".format(rtype))
5840
5841
5842 resource1, rname1 = create_and_register_resource("{rtype}")
5843 resource2, rname2 = create_and_register_resource("{rtype}")
5844
5845 os.write({w}, rname1.encode("ascii") + b"\\n")
5846 os.write({w}, rname2.encode("ascii") + b"\\n")
5847
5848 time.sleep(10)
5849 '''
5850 for rtype in resource_tracker._CLEANUP_FUNCS:
5851 with self.subTest(rtype=rtype):
5852 if rtype in ("noop", "dummy"):
5853 # Artefact resource type used by the resource_tracker
5854 # or tests
5855 continue
5856 r, w = os.pipe()
5857 p = subprocess.Popen([sys.executable,
5858 '-E', '-c', cmd.format(w=w, rtype=rtype)],
5859 pass_fds=[w],
5860 stderr=subprocess.PIPE)
5861 os.close(w)
5862 with open(r, 'rb', closefd=True) as f:
5863 name1 = f.readline().rstrip().decode('ascii')
5864 name2 = f.readline().rstrip().decode('ascii')
5865 _resource_unlink(name1, rtype)
5866 p.terminate()
5867 p.wait()
5868
5869 err_msg = (f"A {rtype} resource was leaked after a process was "
5870 f"abruptly terminated")
5871 for _ in support.sleeping_retry(support.SHORT_TIMEOUT,
5872 err_msg):
5873 try:
5874 _resource_unlink(name2, rtype)
5875 except OSError as e:
5876 # docs say it should be ENOENT, but OSX seems to give
5877 # EINVAL
5878 self.assertIn(e.errno, (errno.ENOENT, errno.EINVAL))
5879 break
5880
5881 err = p.stderr.read().decode('utf-8')
5882 p.stderr.close()
5883 expected = ('resource_tracker: There appear to be 2 leaked {} '
5884 'objects'.format(
5885 rtype))
5886 self.assertRegex(err, expected)
5887 self.assertRegex(err, r'resource_tracker: %r: \[Errno' % name1)
5888
5889 def check_resource_tracker_death(self, signum, should_die):
5890 # bpo-31310: if the semaphore tracker process has died, it should
5891 # be restarted implicitly.
5892 from multiprocessing.resource_tracker import _resource_tracker
5893 pid = _resource_tracker._pid
5894 if pid is not None:
5895 os.kill(pid, signal.SIGKILL)
5896 support.wait_process(pid, exitcode=-signal.SIGKILL)
5897 with warnings.catch_warnings():
5898 warnings.simplefilter("ignore")
5899 _resource_tracker.ensure_running()
5900 pid = _resource_tracker._pid
5901
5902 os.kill(pid, signum)
5903 time.sleep(1.0) # give it time to die
5904
5905 ctx = multiprocessing.get_context("spawn")
5906 with warnings.catch_warnings(record=True) as all_warn:
5907 warnings.simplefilter("always")
5908 sem = ctx.Semaphore()
5909 sem.acquire()
5910 sem.release()
5911 wr = weakref.ref(sem)
5912 # ensure `sem` gets collected, which triggers communication with
5913 # the semaphore tracker
5914 del sem
5915 gc.collect()
5916 self.assertIsNone(wr())
5917 if should_die:
5918 self.assertEqual(len(all_warn), 1)
5919 the_warn = all_warn[0]
5920 self.assertTrue(issubclass(the_warn.category, UserWarning))
5921 self.assertTrue("resource_tracker: process died"
5922 in str(the_warn.message))
5923 else:
5924 self.assertEqual(len(all_warn), 0)
5925
5926 def test_resource_tracker_sigint(self):
5927 # Catchable signal (ignored by semaphore tracker)
5928 self.check_resource_tracker_death(signal.SIGINT, False)
5929
5930 def test_resource_tracker_sigterm(self):
5931 # Catchable signal (ignored by semaphore tracker)
5932 self.check_resource_tracker_death(signal.SIGTERM, False)
5933
5934 @unittest.skipIf(sys.platform.startswith("netbsd"),
5935 "gh-125620: Skip on NetBSD due to long wait for SIGKILL process termination.")
5936 def test_resource_tracker_sigkill(self):
5937 # Uncatchable signal.
5938 self.check_resource_tracker_death(signal.SIGKILL, True)
5939
5940 @staticmethod
5941 def _is_resource_tracker_reused(conn, pid):
5942 from multiprocessing.resource_tracker import _resource_tracker
5943 _resource_tracker.ensure_running()
5944 # The pid should be None in the child process, expect for the fork
5945 # context. It should not be a new value.
5946 reused = _resource_tracker._pid in (None, pid)
5947 reused &= _resource_tracker._check_alive()
5948 conn.send(reused)
5949
5950 def test_resource_tracker_reused(self):
5951 from multiprocessing.resource_tracker import _resource_tracker
5952 _resource_tracker.ensure_running()
5953 pid = _resource_tracker._pid
5954
5955 r, w = multiprocessing.Pipe(duplex=False)
5956 p = multiprocessing.Process(target=self._is_resource_tracker_reused,
5957 args=(w, pid))
5958 p.start()
5959 is_resource_tracker_reused = r.recv()
5960
5961 # Clean up
5962 p.join()
5963 w.close()
5964 r.close()
5965
5966 self.assertTrue(is_resource_tracker_reused)
5967
5968 def test_too_long_name_resource(self):
5969 # gh-96819: Resource names that will make the length of a write to a pipe
5970 # greater than PIPE_BUF are not allowed
5971 rtype = "shared_memory"
5972 too_long_name_resource = "a" * (512 - len(rtype))
5973 with self.assertRaises(ValueError):
5974 resource_tracker.register(too_long_name_resource, rtype)
5975
5976 def _test_resource_tracker_leak_resources(self, cleanup):
5977 # We use a separate instance for testing, since the main global
5978 # _resource_tracker may be used to watch test infrastructure.
5979 from multiprocessing.resource_tracker import ResourceTracker
5980 tracker = ResourceTracker()
5981 tracker.ensure_running()
5982 self.assertTrue(tracker._check_alive())
5983
5984 self.assertIsNone(tracker._exitcode)
5985 tracker.register('somename', 'dummy')
5986 if cleanup:
5987 tracker.unregister('somename', 'dummy')
5988 expected_exit_code = 0
5989 else:
5990 expected_exit_code = 1
5991
5992 self.assertTrue(tracker._check_alive())
5993 self.assertIsNone(tracker._exitcode)
5994 tracker._stop()
5995 self.assertEqual(tracker._exitcode, expected_exit_code)
5996
5997 def test_resource_tracker_exit_code(self):
5998 """
5999 Test the exit code of the resource tracker.
6000
6001 If no leaked resources were found, exit code should be 0, otherwise 1
6002 """
6003 for cleanup in [True, False]:
6004 with self.subTest(cleanup=cleanup):
6005 self._test_resource_tracker_leak_resources(
6006 cleanup=cleanup,
6007 )
6008
6009 @unittest.skipUnless(hasattr(signal, "pthread_sigmask"), "pthread_sigmask is not available")
6010 def test_resource_tracker_blocked_signals(self):
6011 #
6012 # gh-127586: Check that resource_tracker does not override blocked signals of caller.
6013 #
6014 from multiprocessing.resource_tracker import ResourceTracker
6015 orig_sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, set())
6016 signals = {signal.SIGTERM, signal.SIGINT, signal.SIGUSR1}
6017
6018 try:
6019 for sig in signals:
6020 signal.pthread_sigmask(signal.SIG_SETMASK, {sig})
6021 self.assertEqual(signal.pthread_sigmask(signal.SIG_BLOCK, set()), {sig})
6022 tracker = ResourceTracker()
6023 tracker.ensure_running()
6024 self.assertEqual(signal.pthread_sigmask(signal.SIG_BLOCK, set()), {sig})
6025 tracker._stop()
6026 finally:
6027 # restore sigmask to what it was before executing test
6028 signal.pthread_sigmask(signal.SIG_SETMASK, orig_sigmask)
6029
6030 class TestSimpleQueue(unittest.TestCase):
6031
6032 @classmethod
6033 def _test_empty(cls, queue, child_can_start, parent_can_continue):
6034 child_can_start.wait()
6035 # issue 30301, could fail under spawn and forkserver
6036 try:
6037 queue.put(queue.empty())
6038 queue.put(queue.empty())
6039 finally:
6040 parent_can_continue.set()
6041
6042 def test_empty_exceptions(self):
6043 # Assert that checking emptiness of a closed queue raises
6044 # an OSError, independently of whether the queue was used
6045 # or not. This differs from Queue and JoinableQueue.
6046 q = multiprocessing.SimpleQueue()
6047 q.close() # close the pipe
6048 with self.assertRaisesRegex(OSError, 'is closed'):
6049 q.empty()
6050
6051 def test_empty(self):
6052 queue = multiprocessing.SimpleQueue()
6053 child_can_start = multiprocessing.Event()
6054 parent_can_continue = multiprocessing.Event()
6055
6056 proc = multiprocessing.Process(
6057 target=self._test_empty,
6058 args=(queue, child_can_start, parent_can_continue)
6059 )
6060 proc.daemon = True
6061 proc.start()
6062
6063 self.assertTrue(queue.empty())
6064
6065 child_can_start.set()
6066 parent_can_continue.wait()
6067
6068 self.assertFalse(queue.empty())
6069 self.assertEqual(queue.get(), True)
6070 self.assertEqual(queue.get(), False)
6071 self.assertTrue(queue.empty())
6072
6073 proc.join()
6074
6075 def test_close(self):
6076 queue = multiprocessing.SimpleQueue()
6077 queue.close()
6078 # closing a queue twice should not fail
6079 queue.close()
6080
6081 # Test specific to CPython since it tests private attributes
6082 @test.support.cpython_only
6083 def test_closed(self):
6084 queue = multiprocessing.SimpleQueue()
6085 queue.close()
6086 self.assertTrue(queue._reader.closed)
6087 self.assertTrue(queue._writer.closed)
6088
6089
6090 class TestPoolNotLeakOnFailure(unittest.TestCase):
6091
6092 def test_release_unused_processes(self):
6093 # Issue #19675: During pool creation, if we can't create a process,
6094 # don't leak already created ones.
6095 will_fail_in = 3
6096 forked_processes = []
6097
6098 class FailingForkProcess:
6099 def __init__(self, **kwargs):
6100 self.name = 'Fake Process'
6101 self.exitcode = None
6102 self.state = None
6103 forked_processes.append(self)
6104
6105 def start(self):
6106 nonlocal will_fail_in
6107 if will_fail_in <= 0:
6108 raise OSError("Manually induced OSError")
6109 will_fail_in -= 1
6110 self.state = 'started'
6111
6112 def terminate(self):
6113 self.state = 'stopping'
6114
6115 def join(self):
6116 if self.state == 'stopping':
6117 self.state = 'stopped'
6118
6119 def is_alive(self):
6120 return self.state == 'started' or self.state == 'stopping'
6121
6122 with self.assertRaisesRegex(OSError, 'Manually induced OSError'):
6123 p = multiprocessing.pool.Pool(5, context=unittest.mock.MagicMock(
6124 Process=FailingForkProcess))
6125 p.close()
6126 p.join()
6127 self.assertFalse(
6128 any(process.is_alive() for process in forked_processes))
6129
6130
6131 @hashlib_helper.requires_hashdigest('sha256')
6132 class TestSyncManagerTypes(unittest.TestCase):
6133 """Test all the types which can be shared between a parent and a
6134 child process by using a manager which acts as an intermediary
6135 between them.
6136
6137 In the following unit-tests the base type is created in the parent
6138 process, the @classmethod represents the worker process and the
6139 shared object is readable and editable between the two.
6140
6141 # The child.
6142 @classmethod
6143 def _test_list(cls, obj):
6144 assert obj[0] == 5
6145 assert obj.append(6)
6146
6147 # The parent.
6148 def test_list(self):
6149 o = self.manager.list()
6150 o.append(5)
6151 self.run_worker(self._test_list, o)
6152 assert o[1] == 6
6153 """
6154 manager_class = multiprocessing.managers.SyncManager
6155
6156 def setUp(self):
6157 self.manager = self.manager_class()
6158 self.manager.start()
6159 self.proc = None
6160
6161 def tearDown(self):
6162 if self.proc is not None and self.proc.is_alive():
6163 self.proc.terminate()
6164 self.proc.join()
6165 self.manager.shutdown()
6166 self.manager = None
6167 self.proc = None
6168
6169 @classmethod
6170 def setUpClass(cls):
6171 support.reap_children()
6172
6173 tearDownClass = setUpClass
6174
6175 def wait_proc_exit(self):
6176 # Only the manager process should be returned by active_children()
6177 # but this can take a bit on slow machines, so wait a few seconds
6178 # if there are other children too (see #17395).
6179 join_process(self.proc)
6180
6181 timeout = WAIT_ACTIVE_CHILDREN_TIMEOUT
6182 start_time = time.monotonic()
6183 for _ in support.sleeping_retry(timeout, error=False):
6184 if len(multiprocessing.active_children()) <= 1:
6185 break
6186 else:
6187 dt = time.monotonic() - start_time
6188 support.environment_altered = True
6189 support.print_warning(f"multiprocessing.Manager still has "
6190 f"{multiprocessing.active_children()} "
6191 f"active children after {dt:.1f} seconds")
6192
6193 def run_worker(self, worker, obj):
6194 self.proc = multiprocessing.Process(target=worker, args=(obj, ))
6195 self.proc.daemon = True
6196 self.proc.start()
6197 self.wait_proc_exit()
6198 self.assertEqual(self.proc.exitcode, 0)
6199
6200 @classmethod
6201 def _test_event(cls, obj):
6202 assert obj.is_set()
6203 obj.wait()
6204 obj.clear()
6205 obj.wait(0.001)
6206
6207 def test_event(self):
6208 o = self.manager.Event()
6209 o.set()
6210 self.run_worker(self._test_event, o)
6211 assert not o.is_set()
6212 o.wait(0.001)
6213
6214 @classmethod
6215 def _test_lock(cls, obj):
6216 obj.acquire()
6217
6218 def test_lock(self, lname="Lock"):
6219 o = getattr(self.manager, lname)()
6220 self.run_worker(self._test_lock, o)
6221 o.release()
6222 self.assertRaises(RuntimeError, o.release) # already released
6223
6224 @classmethod
6225 def _test_rlock(cls, obj):
6226 obj.acquire()
6227 obj.release()
6228
6229 def test_rlock(self, lname="Lock"):
6230 o = getattr(self.manager, lname)()
6231 self.run_worker(self._test_rlock, o)
6232
6233 @classmethod
6234 def _test_semaphore(cls, obj):
6235 obj.acquire()
6236
6237 def test_semaphore(self, sname="Semaphore"):
6238 o = getattr(self.manager, sname)()
6239 self.run_worker(self._test_semaphore, o)
6240 o.release()
6241
6242 def test_bounded_semaphore(self):
6243 self.test_semaphore(sname="BoundedSemaphore")
6244
6245 @classmethod
6246 def _test_condition(cls, obj):
6247 obj.acquire()
6248 obj.release()
6249
6250 def test_condition(self):
6251 o = self.manager.Condition()
6252 self.run_worker(self._test_condition, o)
6253
6254 @classmethod
6255 def _test_barrier(cls, obj):
6256 assert obj.parties == 5
6257 obj.reset()
6258
6259 def test_barrier(self):
6260 o = self.manager.Barrier(5)
6261 self.run_worker(self._test_barrier, o)
6262
6263 @classmethod
6264 def _test_pool(cls, obj):
6265 # TODO: fix https://bugs.python.org/issue35919
6266 with obj:
6267 pass
6268
6269 def test_pool(self):
6270 o = self.manager.Pool(processes=4)
6271 self.run_worker(self._test_pool, o)
6272
6273 @classmethod
6274 def _test_queue(cls, obj):
6275 assert obj.qsize() == 2
6276 assert obj.full()
6277 assert not obj.empty()
6278 assert obj.get() == 5
6279 assert not obj.empty()
6280 assert obj.get() == 6
6281 assert obj.empty()
6282
6283 def test_queue(self, qname="Queue"):
6284 o = getattr(self.manager, qname)(2)
6285 o.put(5)
6286 o.put(6)
6287 self.run_worker(self._test_queue, o)
6288 assert o.empty()
6289 assert not o.full()
6290
6291 def test_joinable_queue(self):
6292 self.test_queue("JoinableQueue")
6293
6294 @classmethod
6295 def _test_list(cls, obj):
6296 case = unittest.TestCase()
6297 case.assertEqual(obj[0], 5)
6298 case.assertEqual(obj.count(5), 1)
6299 case.assertEqual(obj.index(5), 0)
6300 obj.sort()
6301 obj.reverse()
6302 for x in obj:
6303 pass
6304 case.assertEqual(len(obj), 1)
6305 case.assertEqual(obj.pop(0), 5)
6306
6307 def test_list(self):
6308 o = self.manager.list()
6309 o.append(5)
6310 self.run_worker(self._test_list, o)
6311 self.assertIsNotNone(o)
6312 self.assertEqual(len(o), 0)
6313
6314 @classmethod
6315 def _test_dict(cls, obj):
6316 case = unittest.TestCase()
6317 case.assertEqual(len(obj), 1)
6318 case.assertEqual(obj['foo'], 5)
6319 case.assertEqual(obj.get('foo'), 5)
6320 case.assertListEqual(list(obj.items()), [('foo', 5)])
6321 case.assertListEqual(list(obj.keys()), ['foo'])
6322 case.assertListEqual(list(obj.values()), [5])
6323 case.assertDictEqual(obj.copy(), {'foo': 5})
6324 case.assertTupleEqual(obj.popitem(), ('foo', 5))
6325
6326 def test_dict(self):
6327 o = self.manager.dict()
6328 o['foo'] = 5
6329 self.run_worker(self._test_dict, o)
6330 self.assertIsNotNone(o)
6331 self.assertEqual(len(o), 0)
6332
6333 @classmethod
6334 def _test_value(cls, obj):
6335 case = unittest.TestCase()
6336 case.assertEqual(obj.value, 1)
6337 case.assertEqual(obj.get(), 1)
6338 obj.set(2)
6339
6340 def test_value(self):
6341 o = self.manager.Value('i', 1)
6342 self.run_worker(self._test_value, o)
6343 self.assertEqual(o.value, 2)
6344 self.assertEqual(o.get(), 2)
6345
6346 @classmethod
6347 def _test_array(cls, obj):
6348 case = unittest.TestCase()
6349 case.assertEqual(obj[0], 0)
6350 case.assertEqual(obj[1], 1)
6351 case.assertEqual(len(obj), 2)
6352 case.assertListEqual(list(obj), [0, 1])
6353
6354 def test_array(self):
6355 o = self.manager.Array('i', [0, 1])
6356 self.run_worker(self._test_array, o)
6357
6358 @classmethod
6359 def _test_namespace(cls, obj):
6360 case = unittest.TestCase()
6361 case.assertEqual(obj.x, 0)
6362 case.assertEqual(obj.y, 1)
6363
6364 def test_namespace(self):
6365 o = self.manager.Namespace()
6366 o.x = 0
6367 o.y = 1
6368 self.run_worker(self._test_namespace, o)
6369
6370
6371 class TestNamedResource(unittest.TestCase):
6372 @only_run_in_spawn_testsuite("spawn specific test.")
6373 def test_global_named_resource_spawn(self):
6374 #
6375 # gh-90549: Check that global named resources in main module
6376 # will not leak by a subprocess, in spawn context.
6377 #
6378 testfn = os_helper.TESTFN
6379 self.addCleanup(os_helper.unlink, testfn)
6380 with open(testfn, 'w', encoding='utf-8') as f:
6381 f.write(textwrap.dedent('''\
6382 import multiprocessing as mp
6383 ctx = mp.get_context('spawn')
6384 global_resource = ctx.Semaphore()
6385 def submain(): pass
6386 if __name__ == '__main__':
6387 p = ctx.Process(target=submain)
6388 p.start()
6389 p.join()
6390 '''))
6391 rc, out, err = script_helper.assert_python_ok(testfn)
6392 # on error, err = 'UserWarning: resource_tracker: There appear to
6393 # be 1 leaked semaphore objects to clean up at shutdown'
6394 self.assertFalse(err, msg=err.decode('utf-8'))
6395
6396
6397 class _TestAtExit(BaseTestCase):
6398
6399 ALLOWED_TYPES = ('processes',)
6400
6401 @classmethod
6402 def _write_file_at_exit(self, output_path):
6403 import atexit
6404 def exit_handler():
6405 with open(output_path, 'w') as f:
6406 f.write("deadbeef")
6407 atexit.register(exit_handler)
6408
6409 def test_atexit(self):
6410 # gh-83856
6411 with os_helper.temp_dir() as temp_dir:
6412 output_path = os.path.join(temp_dir, 'output.txt')
6413 p = self.Process(target=self._write_file_at_exit, args=(output_path,))
6414 p.start()
6415 p.join()
6416 with open(output_path) as f:
6417 self.assertEqual(f.read(), 'deadbeef')
6418
6419
6420 class _TestSpawnedSysPath(BaseTestCase):
6421 """Test that sys.path is setup in forkserver and spawn processes."""
6422
6423 ALLOWED_TYPES = {'processes'}
6424 # Not applicable to fork which inherits everything from the process as is.
6425 START_METHODS = {"forkserver", "spawn"}
6426
6427 def setUp(self):
6428 self._orig_sys_path = list(sys.path)
6429 self._temp_dir = tempfile.mkdtemp(prefix="test_sys_path-")
6430 self._mod_name = "unique_test_mod"
6431 module_path = os.path.join(self._temp_dir, f"{self._mod_name}.py")
6432 with open(module_path, "w", encoding="utf-8") as mod:
6433 mod.write("# A simple test module\n")
6434 sys.path[:] = [p for p in sys.path if p] # remove any existing ""s
6435 sys.path.insert(0, self._temp_dir)
6436 sys.path.insert(0, "") # Replaced with an abspath in child.
6437 self.assertIn(self.start_method, self.START_METHODS)
6438 self._ctx = multiprocessing.get_context(self.start_method)
6439
6440 def tearDown(self):
6441 sys.path[:] = self._orig_sys_path
6442 shutil.rmtree(self._temp_dir, ignore_errors=True)
6443
6444 @staticmethod
6445 def enq_imported_module_names(queue):
6446 queue.put(tuple(sys.modules))
6447
6448 def test_forkserver_preload_imports_sys_path(self):
6449 if self._ctx.get_start_method() != "forkserver":
6450 self.skipTest("forkserver specific test.")
6451 self.assertNotIn(self._mod_name, sys.modules)
6452 multiprocessing.forkserver._forkserver._stop() # Must be fresh.
6453 self._ctx.set_forkserver_preload(
6454 ["test.test_multiprocessing_forkserver", self._mod_name])
6455 q = self._ctx.Queue()
6456 proc = self._ctx.Process(
6457 target=self.enq_imported_module_names, args=(q,))
6458 proc.start()
6459 proc.join()
6460 child_imported_modules = q.get()
6461 q.close()
6462 self.assertIn(self._mod_name, child_imported_modules)
6463
6464 @staticmethod
6465 def enq_sys_path_and_import(queue, mod_name):
6466 queue.put(sys.path)
6467 try:
6468 importlib.import_module(mod_name)
6469 except ImportError as exc:
6470 queue.put(exc)
6471 else:
6472 queue.put(None)
6473
6474 def test_child_sys_path(self):
6475 q = self._ctx.Queue()
6476 proc = self._ctx.Process(
6477 target=self.enq_sys_path_and_import, args=(q, self._mod_name))
6478 proc.start()
6479 proc.join()
6480 child_sys_path = q.get()
6481 import_error = q.get()
6482 q.close()
6483 self.assertNotIn("", child_sys_path) # replaced by an abspath
6484 self.assertIn(self._temp_dir, child_sys_path) # our addition
6485 # ignore the first element, it is the absolute "" replacement
6486 self.assertEqual(child_sys_path[1:], sys.path[1:])
6487 self.assertIsNone(import_error, msg=f"child could not import {self._mod_name}")
6488
6489 def test_std_streams_flushed_after_preload(self):
6490 # gh-135335: Check fork server flushes standard streams after
6491 # preloading modules
6492 if multiprocessing.get_start_method() != "forkserver":
6493 self.skipTest("forkserver specific test")
6494
6495 name = os.path.join(os.path.dirname(__file__), 'mp_preload_flush.py')
6496 _, out, err = test.support.script_helper.assert_python_ok(name)
6497
6498 # Check stderr first, as it is more likely to be useful to see in the
6499 # event of a failure.
6500 self.assertEqual(err.decode().rstrip(), '__main____mp_main__')
6501 self.assertEqual(out.decode().rstrip(), '__main____mp_main__')
6502
6503
6504 class MiscTestCase(unittest.TestCase):
6505 def test__all__(self):
6506 # Just make sure names in not_exported are excluded
6507 support.check__all__(self, multiprocessing, extra=multiprocessing.__all__,
6508 not_exported=['SUBDEBUG', 'SUBWARNING'])
6509
6510 @only_run_in_spawn_testsuite("avoids redundant testing.")
6511 def test_spawn_sys_executable_none_allows_import(self):
6512 # Regression test for a bug introduced in
6513 # https://github.com/python/cpython/issues/90876 that caused an
6514 # ImportError in multiprocessing when sys.executable was None.
6515 # This can be true in embedded environments.
6516 rc, out, err = script_helper.assert_python_ok(
6517 "-c",
6518 """if 1:
6519 import sys
6520 sys.executable = None
6521 assert "multiprocessing" not in sys.modules, "already imported!"
6522 import multiprocessing
6523 import multiprocessing.spawn # This should not fail\n""",
6524 )
6525 self.assertEqual(rc, 0)
6526 self.assertFalse(err, msg=err.decode('utf-8'))
6527
6528 def test_large_pool(self):
6529 #
6530 # gh-89240: Check that large pools are always okay
6531 #
6532 testfn = os_helper.TESTFN
6533 self.addCleanup(os_helper.unlink, testfn)
6534 with open(testfn, 'w', encoding='utf-8') as f:
6535 f.write(textwrap.dedent('''\
6536 import multiprocessing
6537 def f(x): return x*x
6538 if __name__ == '__main__':
6539 with multiprocessing.Pool(200) as p:
6540 print(sum(p.map(f, range(1000))))
6541 '''))
6542 rc, out, err = script_helper.assert_python_ok(testfn)
6543 self.assertEqual("332833500", out.decode('utf-8').strip())
6544 self.assertFalse(err, msg=err.decode('utf-8'))
6545
6546 def test_forked_thread_not_started(self):
6547 # gh-134381: Ensure that a thread that has not been started yet in
6548 # the parent process can be started within a forked child process.
6549
6550 if multiprocessing.get_start_method() != "fork":
6551 self.skipTest("fork specific test")
6552
6553 q = multiprocessing.Queue()
6554 t = threading.Thread(target=lambda: q.put("done"), daemon=True)
6555
6556 def child():
6557 t.start()
6558 t.join()
6559
6560 p = multiprocessing.Process(target=child)
6561 p.start()
6562 p.join(support.SHORT_TIMEOUT)
6563
6564 self.assertEqual(p.exitcode, 0)
6565 self.assertEqual(q.get_nowait(), "done")
6566 close_queue(q)
6567
6568 def test_preload_main(self):
6569 # gh-126631: Check that __main__ can be pre-loaded
6570 if multiprocessing.get_start_method() != "forkserver":
6571 self.skipTest("forkserver specific test")
6572
6573 name = os.path.join(os.path.dirname(__file__), 'mp_preload_main.py')
6574 _, out, err = test.support.script_helper.assert_python_ok(name)
6575 self.assertEqual(err, b'')
6576
6577 # The trailing empty string comes from split() on output ending with \n
6578 out = out.decode().split("\n")
6579 self.assertEqual(out, ['__main__', '__mp_main__', 'f', 'f', ''])
6580
6581 def test_preload_main_sys_argv(self):
6582 # gh-143706: Check that sys.argv is set before __main__ is pre-loaded
6583 if multiprocessing.get_start_method() != "forkserver":
6584 self.skipTest("forkserver specific test")
6585
6586 name = os.path.join(os.path.dirname(__file__), 'mp_preload_sysargv.py')
6587 _, out, err = test.support.script_helper.assert_python_ok(
6588 name, 'foo', 'bar')
6589 self.assertEqual(err, b'')
6590
6591 out = out.decode().split("\n")
6592 expected_argv = "['foo', 'bar']"
6593 self.assertEqual(out, [
6594 f"module:{expected_argv}",
6595 f"fun:{expected_argv}",
6596 f"module:{expected_argv}",
6597 f"fun:{expected_argv}",
6598 '',
6599 ])
6600
6601 #
6602 # Mixins
6603 #
6604
6605 class BaseMixin(object):
6606 @classmethod
6607 def setUpClass(cls):
6608 cls.dangling = (multiprocessing.process._dangling.copy(),
6609 threading._dangling.copy())
6610
6611 @classmethod
6612 def tearDownClass(cls):
6613 # bpo-26762: Some multiprocessing objects like Pool create reference
6614 # cycles. Trigger a garbage collection to break these cycles.
6615 test.support.gc_collect()
6616
6617 processes = set(multiprocessing.process._dangling) - set(cls.dangling[0])
6618 if processes:
6619 test.support.environment_altered = True
6620 support.print_warning(f'Dangling processes: {processes}')
6621 processes = None
6622
6623 threads = set(threading._dangling) - set(cls.dangling[1])
6624 if threads:
6625 test.support.environment_altered = True
6626 support.print_warning(f'Dangling threads: {threads}')
6627 threads = None
6628
6629
6630 class ProcessesMixin(BaseMixin):
6631 TYPE = 'processes'
6632 Process = multiprocessing.Process
6633 connection = multiprocessing.connection
6634 current_process = staticmethod(multiprocessing.current_process)
6635 parent_process = staticmethod(multiprocessing.parent_process)
6636 active_children = staticmethod(multiprocessing.active_children)
6637 set_executable = staticmethod(multiprocessing.set_executable)
6638 Pool = staticmethod(multiprocessing.Pool)
6639 Pipe = staticmethod(multiprocessing.Pipe)
6640 Queue = staticmethod(multiprocessing.Queue)
6641 JoinableQueue = staticmethod(multiprocessing.JoinableQueue)
6642 Lock = staticmethod(multiprocessing.Lock)
6643 RLock = staticmethod(multiprocessing.RLock)
6644 Semaphore = staticmethod(multiprocessing.Semaphore)
6645 BoundedSemaphore = staticmethod(multiprocessing.BoundedSemaphore)
6646 Condition = staticmethod(multiprocessing.Condition)
6647 Event = staticmethod(multiprocessing.Event)
6648 Barrier = staticmethod(multiprocessing.Barrier)
6649 Value = staticmethod(multiprocessing.Value)
6650 Array = staticmethod(multiprocessing.Array)
6651 RawValue = staticmethod(multiprocessing.RawValue)
6652 RawArray = staticmethod(multiprocessing.RawArray)
6653
6654
6655 class ManagerMixin(BaseMixin):
6656 TYPE = 'manager'
6657 Process = multiprocessing.Process
6658 Queue = property(operator.attrgetter('manager.Queue'))
6659 JoinableQueue = property(operator.attrgetter('manager.JoinableQueue'))
6660 Lock = property(operator.attrgetter('manager.Lock'))
6661 RLock = property(operator.attrgetter('manager.RLock'))
6662 Semaphore = property(operator.attrgetter('manager.Semaphore'))
6663 BoundedSemaphore = property(operator.attrgetter('manager.BoundedSemaphore'))
6664 Condition = property(operator.attrgetter('manager.Condition'))
6665 Event = property(operator.attrgetter('manager.Event'))
6666 Barrier = property(operator.attrgetter('manager.Barrier'))
6667 Value = property(operator.attrgetter('manager.Value'))
6668 Array = property(operator.attrgetter('manager.Array'))
6669 list = property(operator.attrgetter('manager.list'))
6670 dict = property(operator.attrgetter('manager.dict'))
6671 Namespace = property(operator.attrgetter('manager.Namespace'))
6672
6673 @classmethod
6674 def Pool(cls, *args, **kwds):
6675 return cls.manager.Pool(*args, **kwds)
6676
6677 @classmethod
6678 def setUpClass(cls):
6679 super().setUpClass()
6680 cls.manager = multiprocessing.Manager()
6681
6682 @classmethod
6683 def tearDownClass(cls):
6684 # only the manager process should be returned by active_children()
6685 # but this can take a bit on slow machines, so wait a few seconds
6686 # if there are other children too (see #17395)
6687 timeout = WAIT_ACTIVE_CHILDREN_TIMEOUT
6688 start_time = time.monotonic()
6689 for _ in support.sleeping_retry(timeout, error=False):
6690 if len(multiprocessing.active_children()) <= 1:
6691 break
6692 else:
6693 dt = time.monotonic() - start_time
6694 support.environment_altered = True
6695 support.print_warning(f"multiprocessing.Manager still has "
6696 f"{multiprocessing.active_children()} "
6697 f"active children after {dt:.1f} seconds")
6698
6699 gc.collect() # do garbage collection
6700 if cls.manager._number_of_objects() != 0:
6701 # This is not really an error since some tests do not
6702 # ensure that all processes which hold a reference to a
6703 # managed object have been joined.
6704 test.support.environment_altered = True
6705 support.print_warning('Shared objects which still exist '
6706 'at manager shutdown:')
6707 support.print_warning(cls.manager._debug_info())
6708 cls.manager.shutdown()
6709 cls.manager.join()
6710 cls.manager = None
6711
6712 super().tearDownClass()
6713
6714
6715 class ThreadsMixin(BaseMixin):
6716 TYPE = 'threads'
6717 Process = multiprocessing.dummy.Process
6718 connection = multiprocessing.dummy.connection
6719 current_process = staticmethod(multiprocessing.dummy.current_process)
6720 active_children = staticmethod(multiprocessing.dummy.active_children)
6721 Pool = staticmethod(multiprocessing.dummy.Pool)
6722 Pipe = staticmethod(multiprocessing.dummy.Pipe)
6723 Queue = staticmethod(multiprocessing.dummy.Queue)
6724 JoinableQueue = staticmethod(multiprocessing.dummy.JoinableQueue)
6725 Lock = staticmethod(multiprocessing.dummy.Lock)
6726 RLock = staticmethod(multiprocessing.dummy.RLock)
6727 Semaphore = staticmethod(multiprocessing.dummy.Semaphore)
6728 BoundedSemaphore = staticmethod(multiprocessing.dummy.BoundedSemaphore)
6729 Condition = staticmethod(multiprocessing.dummy.Condition)
6730 Event = staticmethod(multiprocessing.dummy.Event)
6731 Barrier = staticmethod(multiprocessing.dummy.Barrier)
6732 Value = staticmethod(multiprocessing.dummy.Value)
6733 Array = staticmethod(multiprocessing.dummy.Array)
6734
6735 #
6736 # Functions used to create test cases from the base ones in this module
6737 #
6738
6739 def install_tests_in_module_dict(remote_globs, start_method,
6740 only_type=None, exclude_types=False):
6741 __module__ = remote_globs['__name__']
6742 local_globs = globals()
6743 ALL_TYPES = {'processes', 'threads', 'manager'}
6744
6745 for name, base in local_globs.items():
6746 if not isinstance(base, type):
6747 continue
6748 if issubclass(base, BaseTestCase):
6749 if base is BaseTestCase:
6750 continue
6751 assert set(base.ALLOWED_TYPES) <= ALL_TYPES, base.ALLOWED_TYPES
6752 if base.START_METHODS and start_method not in base.START_METHODS:
6753 continue # class not intended for this start method.
6754 for type_ in base.ALLOWED_TYPES:
6755 if only_type and type_ != only_type:
6756 continue
6757 if exclude_types:
6758 continue
6759 newname = 'With' + type_.capitalize() + name[1:]
6760 Mixin = local_globs[type_.capitalize() + 'Mixin']
6761 class Temp(base, Mixin, unittest.TestCase):
6762 pass
6763 if type_ == 'manager':
6764 Temp = hashlib_helper.requires_hashdigest('sha256')(Temp)
6765 Temp.__name__ = Temp.__qualname__ = newname
6766 Temp.__module__ = __module__
6767 Temp.start_method = start_method
6768 remote_globs[newname] = Temp
6769 elif issubclass(base, unittest.TestCase):
6770 if only_type:
6771 continue
6772
6773 class Temp(base, object):
6774 pass
6775 Temp.__name__ = Temp.__qualname__ = name
6776 Temp.__module__ = __module__
6777 remote_globs[name] = Temp
6778
6779 dangling = [None, None]
6780 old_start_method = [None]
6781
6782 def setUpModule():
6783 multiprocessing.set_forkserver_preload(PRELOAD)
6784 multiprocessing.process._cleanup()
6785 dangling[0] = multiprocessing.process._dangling.copy()
6786 dangling[1] = threading._dangling.copy()
6787 old_start_method[0] = multiprocessing.get_start_method(allow_none=True)
6788 try:
6789 multiprocessing.set_start_method(start_method, force=True)
6790 except ValueError:
6791 raise unittest.SkipTest(start_method +
6792 ' start method not supported')
6793
6794 if sys.platform.startswith("linux"):
6795 try:
6796 lock = multiprocessing.RLock()
6797 except OSError:
6798 raise unittest.SkipTest("OSError raises on RLock creation, "
6799 "see issue 3111!")
6800 check_enough_semaphores()
6801 util.get_temp_dir() # creates temp directory
6802 multiprocessing.get_logger().setLevel(LOG_LEVEL)
6803
6804 def tearDownModule():
6805 need_sleep = False
6806
6807 # bpo-26762: Some multiprocessing objects like Pool create reference
6808 # cycles. Trigger a garbage collection to break these cycles.
6809 test.support.gc_collect()
6810
6811 multiprocessing.set_start_method(old_start_method[0], force=True)
6812 # pause a bit so we don't get warning about dangling threads/processes
6813 processes = set(multiprocessing.process._dangling) - set(dangling[0])
6814 if processes:
6815 need_sleep = True
6816 test.support.environment_altered = True
6817 support.print_warning(f'Dangling processes: {processes}')
6818 processes = None
6819
6820 threads = set(threading._dangling) - set(dangling[1])
6821 if threads:
6822 need_sleep = True
6823 test.support.environment_altered = True
6824 support.print_warning(f'Dangling threads: {threads}')
6825 threads = None
6826
6827 # Sleep 500 ms to give time to child processes to complete.
6828 if need_sleep:
6829 time.sleep(0.5)
6830
6831 multiprocessing.util._cleanup_tests()
6832
6833 remote_globs['setUpModule'] = setUpModule
6834 remote_globs['tearDownModule'] = tearDownModule
6835
6836
6837 @unittest.skipIf(not hasattr(_multiprocessing, 'SemLock'), 'SemLock not available')
6838 @unittest.skipIf(sys.platform != "linux", "Linux only")
6839 class SemLockTests(unittest.TestCase):
6840
6841 def test_semlock_subclass(self):
6842 class SemLock(_multiprocessing.SemLock):
6843 pass
6844 name = f'test_semlock_subclass-{os.getpid()}'
6845 s = SemLock(1, 0, 10, name, False)
6846 _multiprocessing.sem_unlink(name)
6847
6848
6849 @unittest.skipUnless(HAS_SHMEM, "requires multiprocessing.shared_memory")
6850 class TestSharedMemoryNames(unittest.TestCase):
6851 @subTests('use_simple_format', (True, False))
6852 def test_that_shared_memory_name_with_colons_has_no_resource_tracker_errors(
6853 self, use_simple_format):
6854 # Test script that creates and cleans up shared memory with colon in name
6855 test_script = textwrap.dedent("""
6856 import sys
6857 from multiprocessing import shared_memory
6858 from multiprocessing import resource_tracker
6859 import time
6860
6861 resource_tracker._resource_tracker._use_simple_format = %s
6862
6863 # Test various patterns of colons in names
6864 test_names = [
6865 "a:b",
6866 "a:b:c",
6867 "test:name:with:many:colons",
6868 ":starts:with:colon",
6869 "ends:with:colon:",
6870 "::double::colons::",
6871 "name\\nwithnewline",
6872 "name-with-trailing-newline\\n",
6873 "\\nname-starts-with-newline",
6874 "colons:and\\nnewlines:mix",
6875 "multi\\nline\\nname",
6876 ]
6877
6878 for name in test_names:
6879 try:
6880 shm = shared_memory.SharedMemory(create=True, size=100, name=name)
6881 shm.buf[:5] = b'hello' # Write something to the shared memory
6882 shm.close()
6883 shm.unlink()
6884
6885 except Exception as e:
6886 print(f"Error with name '{name}': {e}", file=sys.stderr)
6887 sys.exit(1)
6888
6889 print("SUCCESS")
6890 """ % use_simple_format)
6891
6892 rc, out, err = script_helper.assert_python_ok("-c", test_script)
6893 self.assertIn(b"SUCCESS", out)
6894 self.assertNotIn(b"traceback", err.lower(), err)
6895 self.assertNotIn(b"resource_tracker.py", err, err)