blob: 5bf670c8157520f82ca973d0b0968e58d088bad1 [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
Georg Brandl89fad142010-03-14 10:23:39 +000014import unittest
Antoine Pitrou075050f2011-07-15 23:09:13 +020015from test.support import (
Victor Stinner047b7ae2014-10-05 17:37:41 +020016 verbose, import_module, run_unittest, TESTFN, reap_threads,
17 forget, unlink, rmtree)
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000018threading = import_module('threading')
Tim Petersaa222232001-05-22 09:34:27 +000019
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000020def task(N, done, done_tasks, errors):
21 try:
Antoine Pitrou7224d072010-08-22 10:18:36 +000022 # We don't use modulefinder but still import it in order to stress
23 # importing of different modules from several threads.
24 if len(done_tasks) % 2:
25 import modulefinder
26 import random
27 else:
28 import random
29 import modulefinder
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000030 # This will fail if random is not completely initialized
31 x = random.randrange(1, 3)
32 except Exception as e:
33 errors.append(e.with_traceback(None))
34 finally:
Victor Stinner2a129742011-05-30 23:02:52 +020035 done_tasks.append(threading.get_ident())
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000036 finished = len(done_tasks) == N
37 if finished:
Antoine Pitroua62cbf72010-10-13 23:48:39 +000038 done.set()
Tim Petersaa222232001-05-22 09:34:27 +000039
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000040# Create a circular import structure: A -> C -> B -> D -> A
41# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
42
43circular_imports_modules = {
44 'A': """if 1:
45 import time
46 time.sleep(%(delay)s)
47 x = 'a'
48 import C
49 """,
50 'B': """if 1:
51 import time
52 time.sleep(%(delay)s)
53 x = 'b'
54 import D
55 """,
56 'C': """import B""",
57 'D': """import A""",
58}
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000059
Antoine Pitrou7224d072010-08-22 10:18:36 +000060class Finder:
Brett Cannonc091a572013-12-13 16:47:19 -050061 """A dummy finder to detect concurrent access to its find_spec()
Antoine Pitrou7224d072010-08-22 10:18:36 +000062 method."""
63
64 def __init__(self):
65 self.numcalls = 0
66 self.x = 0
Antoine Pitrou075050f2011-07-15 23:09:13 +020067 self.lock = threading.Lock()
Antoine Pitrou7224d072010-08-22 10:18:36 +000068
Brett Cannonc091a572013-12-13 16:47:19 -050069 def find_spec(self, name, path=None, target=None):
70 # Simulate some thread-unsafe behaviour. If calls to find_spec()
Antoine Pitrou7224d072010-08-22 10:18:36 +000071 # are properly serialized, `x` will end up the same as `numcalls`.
72 # Otherwise not.
Antoine Pitrou202b6062012-12-18 22:18:17 +010073 assert imp.lock_held()
Antoine Pitrou7224d072010-08-22 10:18:36 +000074 with self.lock:
75 self.numcalls += 1
76 x = self.x
Antoine Pitroue0b1c232012-12-18 23:03:42 +010077 time.sleep(0.01)
Antoine Pitrou7224d072010-08-22 10:18:36 +000078 self.x = x + 1
79
80class FlushingFinder:
81 """A dummy finder which flushes sys.path_importer_cache when it gets
82 called."""
83
Brett Cannonc091a572013-12-13 16:47:19 -050084 def find_spec(self, name, path=None, target=None):
Antoine Pitrou7224d072010-08-22 10:18:36 +000085 sys.path_importer_cache.clear()
86
87
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000088class ThreadedImportTests(unittest.TestCase):
89
Antoine Pitrou448acd02010-07-16 19:10:38 +000090 def setUp(self):
91 self.old_random = sys.modules.pop('random', None)
92
93 def tearDown(self):
94 # If the `random` module was already initialized, we restore the
95 # old module at the end so that pickling tests don't fail.
96 # See http://bugs.python.org/issue3657#msg110461
97 if self.old_random is not None:
98 sys.modules['random'] = self.old_random
99
Antoine Pitrou7224d072010-08-22 10:18:36 +0000100 def check_parallel_module_init(self):
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000101 if imp.lock_held():
102 # This triggers on, e.g., from test import autotest.
103 raise unittest.SkipTest("can't run when import lock is held")
104
Antoine Pitroua62cbf72010-10-13 23:48:39 +0000105 done = threading.Event()
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000106 for N in (20, 50) * 3:
107 if verbose:
108 print("Trying", N, "threads ...", end=' ')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000109 # Make sure that random and modulefinder get reimported freshly
110 for modname in ['random', 'modulefinder']:
111 try:
112 del sys.modules[modname]
113 except KeyError:
114 pass
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000115 errors = []
116 done_tasks = []
Antoine Pitroua62cbf72010-10-13 23:48:39 +0000117 done.clear()
Victor Stinner3b09d212014-10-01 01:48:05 +0200118 t0 = time.monotonic()
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000119 for i in range(N):
Antoine Pitrou075050f2011-07-15 23:09:13 +0200120 t = threading.Thread(target=task,
121 args=(N, done, done_tasks, errors,))
122 t.start()
Victor Stinnerd7722d72014-10-01 01:45:16 +0200123 completed = done.wait(10 * 60)
Victor Stinner3b09d212014-10-01 01:48:05 +0200124 dt = time.monotonic() - t0
125 if verbose:
126 print("%.1f ms" % (dt*1e3), flush=True, end=" ")
Victor Stinnerb39b9182014-09-04 09:38:38 +0200127 dbg_info = 'done: %s/%s' % (len(done_tasks), N)
128 self.assertFalse(errors, dbg_info)
129 self.assertTrue(completed, dbg_info)
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000130 if verbose:
131 print("OK.")
Tim Petersaa222232001-05-22 09:34:27 +0000132
Antoine Pitrou7224d072010-08-22 10:18:36 +0000133 def test_parallel_module_init(self):
134 self.check_parallel_module_init()
135
136 def test_parallel_meta_path(self):
137 finder = Finder()
Brett Cannon3c6ea1c2012-04-27 13:52:55 -0400138 sys.meta_path.insert(0, finder)
Antoine Pitrou7224d072010-08-22 10:18:36 +0000139 try:
140 self.check_parallel_module_init()
141 self.assertGreater(finder.numcalls, 0)
142 self.assertEqual(finder.x, finder.numcalls)
143 finally:
144 sys.meta_path.remove(finder)
145
146 def test_parallel_path_hooks(self):
147 # Here the Finder instance is only used to check concurrent calls
148 # to path_hook().
149 finder = Finder()
150 # In order for our path hook to be called at each import, we need
151 # to flush the path_importer_cache, which we do by registering a
152 # dedicated meta_path entry.
153 flushing_finder = FlushingFinder()
154 def path_hook(path):
Brett Cannonc091a572013-12-13 16:47:19 -0500155 finder.find_spec('')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000156 raise ImportError
Brett Cannon8923a4d2012-04-24 22:03:46 -0400157 sys.path_hooks.insert(0, path_hook)
Antoine Pitrou7224d072010-08-22 10:18:36 +0000158 sys.meta_path.append(flushing_finder)
159 try:
160 # Flush the cache a first time
Brett Cannonc091a572013-12-13 16:47:19 -0500161 flushing_finder.find_spec('')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000162 numtests = self.check_parallel_module_init()
163 self.assertGreater(finder.numcalls, 0)
164 self.assertEqual(finder.x, finder.numcalls)
165 finally:
166 sys.meta_path.remove(flushing_finder)
167 sys.path_hooks.remove(path_hook)
168
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000169 def test_import_hangers(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000170 # In case this test is run again, make sure the helper module
171 # gets loaded from scratch again.
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000172 try:
173 del sys.modules['test.threaded_import_hangers']
174 except KeyError:
175 pass
176 import test.threaded_import_hangers
177 self.assertFalse(test.threaded_import_hangers.errors)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000179 def test_circular_imports(self):
180 # The goal of this test is to exercise implementations of the import
181 # lock which use a per-module lock, rather than a global lock.
182 # In these implementations, there is a possible deadlock with
183 # circular imports, for example:
184 # - thread 1 imports A (grabbing the lock for A) which imports B
185 # - thread 2 imports B (grabbing the lock for B) which imports A
186 # Such implementations should be able to detect such situations and
187 # resolve them one way or the other, without freezing.
188 # NOTE: our test constructs a slightly less trivial import cycle,
189 # in order to better stress the deadlock avoidance mechanism.
190 delay = 0.5
191 os.mkdir(TESTFN)
192 self.addCleanup(shutil.rmtree, TESTFN)
193 sys.path.insert(0, TESTFN)
194 self.addCleanup(sys.path.remove, TESTFN)
195 for name, contents in circular_imports_modules.items():
196 contents = contents % {'delay': delay}
197 with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
198 f.write(contents.encode('utf-8'))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200199 self.addCleanup(forget, name)
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000200
Antoine Pitrou07edb822012-12-18 23:28:04 +0100201 importlib.invalidate_caches()
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000202 results = []
203 def import_ab():
204 import A
205 results.append(getattr(A, 'x', None))
206 def import_ba():
207 import B
208 results.append(getattr(B, 'x', None))
209 t1 = threading.Thread(target=import_ab)
210 t2 = threading.Thread(target=import_ba)
211 t1.start()
212 t2.start()
213 t1.join()
214 t2.join()
215 self.assertEqual(set(results), {'a', 'b'})
216
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200217 def test_side_effect_import(self):
218 code = """if 1:
219 import threading
220 def target():
221 import random
222 t = threading.Thread(target=target)
223 t.start()
224 t.join()"""
225 sys.path.insert(0, os.curdir)
226 self.addCleanup(sys.path.remove, os.curdir)
Antoine Pitrou314a16b2012-05-17 21:02:54 +0200227 filename = TESTFN + ".py"
228 with open(filename, "wb") as f:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200229 f.write(code.encode('utf-8'))
Antoine Pitrou314a16b2012-05-17 21:02:54 +0200230 self.addCleanup(unlink, filename)
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200231 self.addCleanup(forget, TESTFN)
Victor Stinner047b7ae2014-10-05 17:37:41 +0200232 self.addCleanup(rmtree, '__pycache__')
Antoine Pitrou07edb822012-12-18 23:28:04 +0100233 importlib.invalidate_caches()
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200234 __import__(TESTFN)
235
Tim Petersaa222232001-05-22 09:34:27 +0000236
Antoine Pitrou075050f2011-07-15 23:09:13 +0200237@reap_threads
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000238def test_main():
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200239 old_switchinterval = None
240 try:
241 old_switchinterval = sys.getswitchinterval()
Stefan Krah219c7b92012-10-01 23:21:45 +0200242 sys.setswitchinterval(1e-5)
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200243 except AttributeError:
244 pass
245 try:
246 run_unittest(ThreadedImportTests)
247 finally:
248 if old_switchinterval is not None:
249 sys.setswitchinterval(old_switchinterval)
Tim Peters69232342001-08-30 05:16:13 +0000250
Tim Petersd9742212001-05-22 18:28:25 +0000251if __name__ == "__main__":
252 test_main()