blob: 8607f363db21c0334330d2d431650a0f1fae7f68 [file] [log] [blame]
Tim Petersaa222232001-05-22 09:34:27 +00001# 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
Brett Cannone4f41de2013-06-16 13:13:40 -04008import _imp as imp
Antoine Pitrou0723d2c2010-08-22 20:43:26 +00009import os
Antoine Pitrou07edb822012-12-18 23:28:04 +010010import importlib
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000011import sys
Antoine Pitrou7224d072010-08-22 10:18:36 +000012import time
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000013import shutil
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020014import threading
Georg Brandl89fad142010-03-14 10:23:39 +000015import unittest
Victor Stinnerc5179f62017-06-10 19:41:24 +020016from unittest import mock
Antoine Pitrou075050f2011-07-15 23:09:13 +020017from test.support import (
Victor Stinner466e18e2019-07-01 19:01:52 +020018 verbose, run_unittest, TESTFN, reap_threads,
Serhiy Storchaka263dcd22015-04-01 13:01:14 +030019 forget, unlink, rmtree, start_threads)
Tim Petersaa222232001-05-22 09:34:27 +000020
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000021def task(N, done, done_tasks, errors):
22 try:
Antoine Pitrou7224d072010-08-22 10:18:36 +000023 # We don't use modulefinder but still import it in order to stress
24 # importing of different modules from several threads.
25 if len(done_tasks) % 2:
26 import modulefinder
27 import random
28 else:
29 import random
30 import modulefinder
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000031 # This will fail if random is not completely initialized
32 x = random.randrange(1, 3)
33 except Exception as e:
34 errors.append(e.with_traceback(None))
35 finally:
Victor Stinner2a129742011-05-30 23:02:52 +020036 done_tasks.append(threading.get_ident())
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000037 finished = len(done_tasks) == N
38 if finished:
Antoine Pitroua62cbf72010-10-13 23:48:39 +000039 done.set()
Tim Petersaa222232001-05-22 09:34:27 +000040
Victor Stinnerc5179f62017-06-10 19:41:24 +020041def mock_register_at_fork(func):
42 # bpo-30599: Mock os.register_at_fork() when importing the random module,
43 # since this function doesn't allow to unregister callbacks and would leak
44 # memory.
45 return mock.patch('os.register_at_fork', create=True)(func)
46
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000047# Create a circular import structure: A -> C -> B -> D -> A
48# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
49
50circular_imports_modules = {
51 'A': """if 1:
52 import time
53 time.sleep(%(delay)s)
54 x = 'a'
55 import C
56 """,
57 'B': """if 1:
58 import time
59 time.sleep(%(delay)s)
60 x = 'b'
61 import D
62 """,
63 'C': """import B""",
64 'D': """import A""",
65}
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000066
Antoine Pitrou7224d072010-08-22 10:18:36 +000067class Finder:
Brett Cannonc091a572013-12-13 16:47:19 -050068 """A dummy finder to detect concurrent access to its find_spec()
Antoine Pitrou7224d072010-08-22 10:18:36 +000069 method."""
70
71 def __init__(self):
72 self.numcalls = 0
73 self.x = 0
Antoine Pitrou075050f2011-07-15 23:09:13 +020074 self.lock = threading.Lock()
Antoine Pitrou7224d072010-08-22 10:18:36 +000075
Brett Cannonc091a572013-12-13 16:47:19 -050076 def find_spec(self, name, path=None, target=None):
77 # Simulate some thread-unsafe behaviour. If calls to find_spec()
Antoine Pitrou7224d072010-08-22 10:18:36 +000078 # are properly serialized, `x` will end up the same as `numcalls`.
79 # Otherwise not.
Antoine Pitrou202b6062012-12-18 22:18:17 +010080 assert imp.lock_held()
Antoine Pitrou7224d072010-08-22 10:18:36 +000081 with self.lock:
82 self.numcalls += 1
83 x = self.x
Antoine Pitroue0b1c232012-12-18 23:03:42 +010084 time.sleep(0.01)
Antoine Pitrou7224d072010-08-22 10:18:36 +000085 self.x = x + 1
86
87class FlushingFinder:
88 """A dummy finder which flushes sys.path_importer_cache when it gets
89 called."""
90
Brett Cannonc091a572013-12-13 16:47:19 -050091 def find_spec(self, name, path=None, target=None):
Antoine Pitrou7224d072010-08-22 10:18:36 +000092 sys.path_importer_cache.clear()
93
94
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000095class ThreadedImportTests(unittest.TestCase):
96
Antoine Pitrou448acd02010-07-16 19:10:38 +000097 def setUp(self):
98 self.old_random = sys.modules.pop('random', None)
99
100 def tearDown(self):
101 # If the `random` module was already initialized, we restore the
102 # old module at the end so that pickling tests don't fail.
103 # See http://bugs.python.org/issue3657#msg110461
104 if self.old_random is not None:
105 sys.modules['random'] = self.old_random
106
Victor Stinnerc5179f62017-06-10 19:41:24 +0200107 @mock_register_at_fork
108 def check_parallel_module_init(self, mock_os):
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000109 if imp.lock_held():
110 # This triggers on, e.g., from test import autotest.
111 raise unittest.SkipTest("can't run when import lock is held")
112
Antoine Pitroua62cbf72010-10-13 23:48:39 +0000113 done = threading.Event()
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000114 for N in (20, 50) * 3:
115 if verbose:
116 print("Trying", N, "threads ...", end=' ')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000117 # Make sure that random and modulefinder get reimported freshly
118 for modname in ['random', 'modulefinder']:
119 try:
120 del sys.modules[modname]
121 except KeyError:
122 pass
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000123 errors = []
124 done_tasks = []
Antoine Pitroua62cbf72010-10-13 23:48:39 +0000125 done.clear()
Victor Stinner3b09d212014-10-01 01:48:05 +0200126 t0 = time.monotonic()
Serhiy Storchaka263dcd22015-04-01 13:01:14 +0300127 with start_threads(threading.Thread(target=task,
128 args=(N, done, done_tasks, errors,))
129 for i in range(N)):
130 pass
Victor Stinnerd7722d72014-10-01 01:45:16 +0200131 completed = done.wait(10 * 60)
Victor Stinner3b09d212014-10-01 01:48:05 +0200132 dt = time.monotonic() - t0
133 if verbose:
134 print("%.1f ms" % (dt*1e3), flush=True, end=" ")
Victor Stinnerb39b9182014-09-04 09:38:38 +0200135 dbg_info = 'done: %s/%s' % (len(done_tasks), N)
136 self.assertFalse(errors, dbg_info)
137 self.assertTrue(completed, dbg_info)
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000138 if verbose:
139 print("OK.")
Tim Petersaa222232001-05-22 09:34:27 +0000140
Antoine Pitrou7224d072010-08-22 10:18:36 +0000141 def test_parallel_module_init(self):
142 self.check_parallel_module_init()
143
144 def test_parallel_meta_path(self):
145 finder = Finder()
Brett Cannon3c6ea1c2012-04-27 13:52:55 -0400146 sys.meta_path.insert(0, finder)
Antoine Pitrou7224d072010-08-22 10:18:36 +0000147 try:
148 self.check_parallel_module_init()
149 self.assertGreater(finder.numcalls, 0)
150 self.assertEqual(finder.x, finder.numcalls)
151 finally:
152 sys.meta_path.remove(finder)
153
154 def test_parallel_path_hooks(self):
155 # Here the Finder instance is only used to check concurrent calls
156 # to path_hook().
157 finder = Finder()
158 # In order for our path hook to be called at each import, we need
159 # to flush the path_importer_cache, which we do by registering a
160 # dedicated meta_path entry.
161 flushing_finder = FlushingFinder()
162 def path_hook(path):
Brett Cannonc091a572013-12-13 16:47:19 -0500163 finder.find_spec('')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000164 raise ImportError
Brett Cannon8923a4d2012-04-24 22:03:46 -0400165 sys.path_hooks.insert(0, path_hook)
Antoine Pitrou7224d072010-08-22 10:18:36 +0000166 sys.meta_path.append(flushing_finder)
167 try:
168 # Flush the cache a first time
Brett Cannonc091a572013-12-13 16:47:19 -0500169 flushing_finder.find_spec('')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000170 numtests = self.check_parallel_module_init()
171 self.assertGreater(finder.numcalls, 0)
172 self.assertEqual(finder.x, finder.numcalls)
173 finally:
174 sys.meta_path.remove(flushing_finder)
175 sys.path_hooks.remove(path_hook)
176
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000177 def test_import_hangers(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178 # In case this test is run again, make sure the helper module
179 # gets loaded from scratch again.
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000180 try:
181 del sys.modules['test.threaded_import_hangers']
182 except KeyError:
183 pass
184 import test.threaded_import_hangers
185 self.assertFalse(test.threaded_import_hangers.errors)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000186
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000187 def test_circular_imports(self):
188 # The goal of this test is to exercise implementations of the import
189 # lock which use a per-module lock, rather than a global lock.
190 # In these implementations, there is a possible deadlock with
191 # circular imports, for example:
192 # - thread 1 imports A (grabbing the lock for A) which imports B
193 # - thread 2 imports B (grabbing the lock for B) which imports A
194 # Such implementations should be able to detect such situations and
195 # resolve them one way or the other, without freezing.
196 # NOTE: our test constructs a slightly less trivial import cycle,
197 # in order to better stress the deadlock avoidance mechanism.
198 delay = 0.5
199 os.mkdir(TESTFN)
200 self.addCleanup(shutil.rmtree, TESTFN)
201 sys.path.insert(0, TESTFN)
202 self.addCleanup(sys.path.remove, TESTFN)
203 for name, contents in circular_imports_modules.items():
204 contents = contents % {'delay': delay}
205 with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
206 f.write(contents.encode('utf-8'))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200207 self.addCleanup(forget, name)
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000208
Antoine Pitrou07edb822012-12-18 23:28:04 +0100209 importlib.invalidate_caches()
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000210 results = []
211 def import_ab():
212 import A
213 results.append(getattr(A, 'x', None))
214 def import_ba():
215 import B
216 results.append(getattr(B, 'x', None))
217 t1 = threading.Thread(target=import_ab)
218 t2 = threading.Thread(target=import_ba)
219 t1.start()
220 t2.start()
221 t1.join()
222 t2.join()
223 self.assertEqual(set(results), {'a', 'b'})
224
Victor Stinnerc5179f62017-06-10 19:41:24 +0200225 @mock_register_at_fork
226 def test_side_effect_import(self, mock_os):
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200227 code = """if 1:
228 import threading
229 def target():
230 import random
231 t = threading.Thread(target=target)
232 t.start()
Victor Stinner41bbd822017-08-22 18:05:32 +0200233 t.join()
234 t = None"""
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200235 sys.path.insert(0, os.curdir)
236 self.addCleanup(sys.path.remove, os.curdir)
Antoine Pitrou314a16b2012-05-17 21:02:54 +0200237 filename = TESTFN + ".py"
238 with open(filename, "wb") as f:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200239 f.write(code.encode('utf-8'))
Antoine Pitrou314a16b2012-05-17 21:02:54 +0200240 self.addCleanup(unlink, filename)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200241 self.addCleanup(forget, TESTFN)
Victor Stinner047b7ae2014-10-05 17:37:41 +0200242 self.addCleanup(rmtree, '__pycache__')
Antoine Pitrou07edb822012-12-18 23:28:04 +0100243 importlib.invalidate_caches()
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200244 __import__(TESTFN)
Victor Stinner41bbd822017-08-22 18:05:32 +0200245 del sys.modules[TESTFN]
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200246
Tim Petersaa222232001-05-22 09:34:27 +0000247
Antoine Pitrou075050f2011-07-15 23:09:13 +0200248@reap_threads
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000249def test_main():
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200250 old_switchinterval = None
251 try:
252 old_switchinterval = sys.getswitchinterval()
Stefan Krah219c7b92012-10-01 23:21:45 +0200253 sys.setswitchinterval(1e-5)
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200254 except AttributeError:
255 pass
256 try:
257 run_unittest(ThreadedImportTests)
258 finally:
259 if old_switchinterval is not None:
260 sys.setswitchinterval(old_switchinterval)
Tim Peters69232342001-08-30 05:16:13 +0000261
Tim Petersd9742212001-05-22 18:28:25 +0000262if __name__ == "__main__":
263 test_main()