• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# This is a variant of the very old (early 90's) file
2# Demo/threads/bug.py.  It simply provokes a number of threads into
3# trying to import the same module "at the same time".
4# There are no pleasant failure modes -- most likely is that Python
5# complains several times about module random having no attribute
6# randrange, and then Python hangs.
7
8import _imp as imp
9import os
10import importlib
11import sys
12import time
13import shutil
14import threading
15import unittest
16from unittest import mock
17from test.support import verbose
18from test.support.import_helper import forget
19from test.support.os_helper import (TESTFN, unlink, rmtree)
20from test.support import script_helper, threading_helper
21
22def task(N, done, done_tasks, errors):
23    try:
24        # We don't use modulefinder but still import it in order to stress
25        # importing of different modules from several threads.
26        if len(done_tasks) % 2:
27            import modulefinder
28            import random
29        else:
30            import random
31            import modulefinder
32        # This will fail if random is not completely initialized
33        x = random.randrange(1, 3)
34    except Exception as e:
35        errors.append(e.with_traceback(None))
36    finally:
37        done_tasks.append(threading.get_ident())
38        finished = len(done_tasks) == N
39        if finished:
40            done.set()
41
42def mock_register_at_fork(func):
43    # bpo-30599: Mock os.register_at_fork() when importing the random module,
44    # since this function doesn't allow to unregister callbacks and would leak
45    # memory.
46    return mock.patch('os.register_at_fork', create=True)(func)
47
48# Create a circular import structure: A -> C -> B -> D -> A
49# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
50
51circular_imports_modules = {
52    'A': """if 1:
53        import time
54        time.sleep(%(delay)s)
55        x = 'a'
56        import C
57        """,
58    'B': """if 1:
59        import time
60        time.sleep(%(delay)s)
61        x = 'b'
62        import D
63        """,
64    'C': """import B""",
65    'D': """import A""",
66}
67
68class Finder:
69    """A dummy finder to detect concurrent access to its find_spec()
70    method."""
71
72    def __init__(self):
73        self.numcalls = 0
74        self.x = 0
75        self.lock = threading.Lock()
76
77    def find_spec(self, name, path=None, target=None):
78        # Simulate some thread-unsafe behaviour. If calls to find_spec()
79        # are properly serialized, `x` will end up the same as `numcalls`.
80        # Otherwise not.
81        assert imp.lock_held()
82        with self.lock:
83            self.numcalls += 1
84        x = self.x
85        time.sleep(0.01)
86        self.x = x + 1
87
88class FlushingFinder:
89    """A dummy finder which flushes sys.path_importer_cache when it gets
90    called."""
91
92    def find_spec(self, name, path=None, target=None):
93        sys.path_importer_cache.clear()
94
95
96class ThreadedImportTests(unittest.TestCase):
97
98    def setUp(self):
99        self.old_random = sys.modules.pop('random', None)
100
101    def tearDown(self):
102        # If the `random` module was already initialized, we restore the
103        # old module at the end so that pickling tests don't fail.
104        # See http://bugs.python.org/issue3657#msg110461
105        if self.old_random is not None:
106            sys.modules['random'] = self.old_random
107
108    @mock_register_at_fork
109    def check_parallel_module_init(self, mock_os):
110        if imp.lock_held():
111            # This triggers on, e.g., from test import autotest.
112            raise unittest.SkipTest("can't run when import lock is held")
113
114        done = threading.Event()
115        for N in (20, 50) * 3:
116            if verbose:
117                print("Trying", N, "threads ...", end=' ')
118            # Make sure that random and modulefinder get reimported freshly
119            for modname in ['random', 'modulefinder']:
120                try:
121                    del sys.modules[modname]
122                except KeyError:
123                    pass
124            errors = []
125            done_tasks = []
126            done.clear()
127            t0 = time.monotonic()
128            with threading_helper.start_threads(
129                    threading.Thread(target=task, args=(N, done, done_tasks, errors,))
130                    for i in range(N)):
131                pass
132            completed = done.wait(10 * 60)
133            dt = time.monotonic() - t0
134            if verbose:
135                print("%.1f ms" % (dt*1e3), flush=True, end=" ")
136            dbg_info = 'done: %s/%s' % (len(done_tasks), N)
137            self.assertFalse(errors, dbg_info)
138            self.assertTrue(completed, dbg_info)
139            if verbose:
140                print("OK.")
141
142    def test_parallel_module_init(self):
143        self.check_parallel_module_init()
144
145    def test_parallel_meta_path(self):
146        finder = Finder()
147        sys.meta_path.insert(0, finder)
148        try:
149            self.check_parallel_module_init()
150            self.assertGreater(finder.numcalls, 0)
151            self.assertEqual(finder.x, finder.numcalls)
152        finally:
153            sys.meta_path.remove(finder)
154
155    def test_parallel_path_hooks(self):
156        # Here the Finder instance is only used to check concurrent calls
157        # to path_hook().
158        finder = Finder()
159        # In order for our path hook to be called at each import, we need
160        # to flush the path_importer_cache, which we do by registering a
161        # dedicated meta_path entry.
162        flushing_finder = FlushingFinder()
163        def path_hook(path):
164            finder.find_spec('')
165            raise ImportError
166        sys.path_hooks.insert(0, path_hook)
167        sys.meta_path.append(flushing_finder)
168        try:
169            # Flush the cache a first time
170            flushing_finder.find_spec('')
171            numtests = self.check_parallel_module_init()
172            self.assertGreater(finder.numcalls, 0)
173            self.assertEqual(finder.x, finder.numcalls)
174        finally:
175            sys.meta_path.remove(flushing_finder)
176            sys.path_hooks.remove(path_hook)
177
178    def test_import_hangers(self):
179        # In case this test is run again, make sure the helper module
180        # gets loaded from scratch again.
181        try:
182            del sys.modules['test.test_importlib.threaded_import_hangers']
183        except KeyError:
184            pass
185        import test.test_importlib.threaded_import_hangers
186        self.assertFalse(test.test_importlib.threaded_import_hangers.errors)
187
188    def test_circular_imports(self):
189        # The goal of this test is to exercise implementations of the import
190        # lock which use a per-module lock, rather than a global lock.
191        # In these implementations, there is a possible deadlock with
192        # circular imports, for example:
193        # - thread 1 imports A (grabbing the lock for A) which imports B
194        # - thread 2 imports B (grabbing the lock for B) which imports A
195        # Such implementations should be able to detect such situations and
196        # resolve them one way or the other, without freezing.
197        # NOTE: our test constructs a slightly less trivial import cycle,
198        # in order to better stress the deadlock avoidance mechanism.
199        delay = 0.5
200        os.mkdir(TESTFN)
201        self.addCleanup(shutil.rmtree, TESTFN)
202        sys.path.insert(0, TESTFN)
203        self.addCleanup(sys.path.remove, TESTFN)
204        for name, contents in circular_imports_modules.items():
205            contents = contents % {'delay': delay}
206            with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
207                f.write(contents.encode('utf-8'))
208            self.addCleanup(forget, name)
209
210        importlib.invalidate_caches()
211        results = []
212        def import_ab():
213            import A
214            results.append(getattr(A, 'x', None))
215        def import_ba():
216            import B
217            results.append(getattr(B, 'x', None))
218        t1 = threading.Thread(target=import_ab)
219        t2 = threading.Thread(target=import_ba)
220        t1.start()
221        t2.start()
222        t1.join()
223        t2.join()
224        self.assertEqual(set(results), {'a', 'b'})
225
226    @mock_register_at_fork
227    def test_side_effect_import(self, mock_os):
228        code = """if 1:
229            import threading
230            def target():
231                import random
232            t = threading.Thread(target=target)
233            t.start()
234            t.join()
235            t = None"""
236        sys.path.insert(0, os.curdir)
237        self.addCleanup(sys.path.remove, os.curdir)
238        filename = TESTFN + ".py"
239        with open(filename, "wb") as f:
240            f.write(code.encode('utf-8'))
241        self.addCleanup(unlink, filename)
242        self.addCleanup(forget, TESTFN)
243        self.addCleanup(rmtree, '__pycache__')
244        importlib.invalidate_caches()
245        __import__(TESTFN)
246        del sys.modules[TESTFN]
247
248    def test_concurrent_futures_circular_import(self):
249        # Regression test for bpo-43515
250        fn = os.path.join(os.path.dirname(__file__),
251                          'partial', 'cfimport.py')
252        script_helper.assert_python_ok(fn)
253
254    def test_multiprocessing_pool_circular_import(self):
255        # Regression test for bpo-41567
256        fn = os.path.join(os.path.dirname(__file__),
257                          'partial', 'pool_in_threads.py')
258        script_helper.assert_python_ok(fn)
259
260
261def setUpModule():
262    thread_info = threading_helper.threading_setup()
263    unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info)
264    try:
265        old_switchinterval = sys.getswitchinterval()
266        unittest.addModuleCleanup(sys.setswitchinterval, old_switchinterval)
267        sys.setswitchinterval(1e-5)
268    except AttributeError:
269        pass
270
271
272if __name__ == "__main__":
273    unittets.main()
274