Debian Codegraph @

lib-python/3/test/_test_multiprocessing.py

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