Debian Codegraph @

lib-python/3/test/_test_multiprocessing.py

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