blob: 8884fa8182faaf4069a8734ede3b013379511b59 [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
Antoine Pitrou0723d2c2010-08-22 20:43:26 +00008import os
Antoine Pitrou1f9dea02010-07-14 11:52:38 +00009import imp
10import sys
Antoine Pitrou7224d072010-08-22 10:18:36 +000011import time
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000012import shutil
Georg Brandl89fad142010-03-14 10:23:39 +000013import unittest
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000014from test.support import verbose, import_module, run_unittest, TESTFN
Victor Stinner45df8202010-04-28 22:31:17 +000015thread = import_module('_thread')
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000016threading = import_module('threading')
Tim Petersaa222232001-05-22 09:34:27 +000017
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000018def task(N, done, done_tasks, errors):
19 try:
Antoine Pitrou7224d072010-08-22 10:18:36 +000020 # We don't use modulefinder but still import it in order to stress
21 # importing of different modules from several threads.
22 if len(done_tasks) % 2:
23 import modulefinder
24 import random
25 else:
26 import random
27 import modulefinder
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000028 # This will fail if random is not completely initialized
29 x = random.randrange(1, 3)
30 except Exception as e:
31 errors.append(e.with_traceback(None))
32 finally:
33 done_tasks.append(thread.get_ident())
34 finished = len(done_tasks) == N
35 if finished:
36 done.release()
Tim Petersaa222232001-05-22 09:34:27 +000037
Antoine Pitrou0723d2c2010-08-22 20:43:26 +000038# Create a circular import structure: A -> C -> B -> D -> A
39# NOTE: `time` is already loaded and therefore doesn't threaten to deadlock.
40
41circular_imports_modules = {
42 'A': """if 1:
43 import time
44 time.sleep(%(delay)s)
45 x = 'a'
46 import C
47 """,
48 'B': """if 1:
49 import time
50 time.sleep(%(delay)s)
51 x = 'b'
52 import D
53 """,
54 'C': """import B""",
55 'D': """import A""",
56}
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000057
Antoine Pitrou7224d072010-08-22 10:18:36 +000058class Finder:
59 """A dummy finder to detect concurrent access to its find_module()
60 method."""
61
62 def __init__(self):
63 self.numcalls = 0
64 self.x = 0
65 self.lock = thread.allocate_lock()
66
67 def find_module(self, name, path=None):
68 # Simulate some thread-unsafe behaviour. If calls to find_module()
69 # are properly serialized, `x` will end up the same as `numcalls`.
70 # Otherwise not.
71 with self.lock:
72 self.numcalls += 1
73 x = self.x
74 time.sleep(0.1)
75 self.x = x + 1
76
77class FlushingFinder:
78 """A dummy finder which flushes sys.path_importer_cache when it gets
79 called."""
80
81 def find_module(self, name, path=None):
82 sys.path_importer_cache.clear()
83
84
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000085class ThreadedImportTests(unittest.TestCase):
86
Antoine Pitrou448acd02010-07-16 19:10:38 +000087 def setUp(self):
88 self.old_random = sys.modules.pop('random', None)
89
90 def tearDown(self):
91 # If the `random` module was already initialized, we restore the
92 # old module at the end so that pickling tests don't fail.
93 # See http://bugs.python.org/issue3657#msg110461
94 if self.old_random is not None:
95 sys.modules['random'] = self.old_random
96
Antoine Pitrou7224d072010-08-22 10:18:36 +000097 def check_parallel_module_init(self):
Antoine Pitrou1f9dea02010-07-14 11:52:38 +000098 if imp.lock_held():
99 # This triggers on, e.g., from test import autotest.
100 raise unittest.SkipTest("can't run when import lock is held")
101
102 done = thread.allocate_lock()
103 done.acquire()
104 for N in (20, 50) * 3:
105 if verbose:
106 print("Trying", N, "threads ...", end=' ')
Antoine Pitrou7224d072010-08-22 10:18:36 +0000107 # Make sure that random and modulefinder get reimported freshly
108 for modname in ['random', 'modulefinder']:
109 try:
110 del sys.modules[modname]
111 except KeyError:
112 pass
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000113 errors = []
114 done_tasks = []
115 for i in range(N):
116 thread.start_new_thread(task, (N, done, done_tasks, errors,))
117 done.acquire()
118 self.assertFalse(errors)
119 if verbose:
120 print("OK.")
Tim Peters20882dd2002-02-16 07:26:27 +0000121 done.release()
Tim Petersaa222232001-05-22 09:34:27 +0000122
Antoine Pitrou7224d072010-08-22 10:18:36 +0000123 def test_parallel_module_init(self):
124 self.check_parallel_module_init()
125
126 def test_parallel_meta_path(self):
127 finder = Finder()
128 sys.meta_path.append(finder)
129 try:
130 self.check_parallel_module_init()
131 self.assertGreater(finder.numcalls, 0)
132 self.assertEqual(finder.x, finder.numcalls)
133 finally:
134 sys.meta_path.remove(finder)
135
136 def test_parallel_path_hooks(self):
137 # Here the Finder instance is only used to check concurrent calls
138 # to path_hook().
139 finder = Finder()
140 # In order for our path hook to be called at each import, we need
141 # to flush the path_importer_cache, which we do by registering a
142 # dedicated meta_path entry.
143 flushing_finder = FlushingFinder()
144 def path_hook(path):
145 finder.find_module('')
146 raise ImportError
147 sys.path_hooks.append(path_hook)
148 sys.meta_path.append(flushing_finder)
149 try:
150 # Flush the cache a first time
151 flushing_finder.find_module('')
152 numtests = self.check_parallel_module_init()
153 self.assertGreater(finder.numcalls, 0)
154 self.assertEqual(finder.x, finder.numcalls)
155 finally:
156 sys.meta_path.remove(flushing_finder)
157 sys.path_hooks.remove(path_hook)
158
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000159 def test_import_hangers(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000160 # In case this test is run again, make sure the helper module
161 # gets loaded from scratch again.
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000162 try:
163 del sys.modules['test.threaded_import_hangers']
164 except KeyError:
165 pass
166 import test.threaded_import_hangers
167 self.assertFalse(test.threaded_import_hangers.errors)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000168
Antoine Pitrou0723d2c2010-08-22 20:43:26 +0000169 def test_circular_imports(self):
170 # The goal of this test is to exercise implementations of the import
171 # lock which use a per-module lock, rather than a global lock.
172 # In these implementations, there is a possible deadlock with
173 # circular imports, for example:
174 # - thread 1 imports A (grabbing the lock for A) which imports B
175 # - thread 2 imports B (grabbing the lock for B) which imports A
176 # Such implementations should be able to detect such situations and
177 # resolve them one way or the other, without freezing.
178 # NOTE: our test constructs a slightly less trivial import cycle,
179 # in order to better stress the deadlock avoidance mechanism.
180 delay = 0.5
181 os.mkdir(TESTFN)
182 self.addCleanup(shutil.rmtree, TESTFN)
183 sys.path.insert(0, TESTFN)
184 self.addCleanup(sys.path.remove, TESTFN)
185 for name, contents in circular_imports_modules.items():
186 contents = contents % {'delay': delay}
187 with open(os.path.join(TESTFN, name + ".py"), "wb") as f:
188 f.write(contents.encode('utf-8'))
189 self.addCleanup(sys.modules.pop, name, None)
190
191 results = []
192 def import_ab():
193 import A
194 results.append(getattr(A, 'x', None))
195 def import_ba():
196 import B
197 results.append(getattr(B, 'x', None))
198 t1 = threading.Thread(target=import_ab)
199 t2 = threading.Thread(target=import_ba)
200 t1.start()
201 t2.start()
202 t1.join()
203 t2.join()
204 self.assertEqual(set(results), {'a', 'b'})
205
Tim Petersaa222232001-05-22 09:34:27 +0000206
Antoine Pitrou1f9dea02010-07-14 11:52:38 +0000207def test_main():
208 run_unittest(ThreadedImportTests)
Tim Peters69232342001-08-30 05:16:13 +0000209
Tim Petersd9742212001-05-22 18:28:25 +0000210if __name__ == "__main__":
211 test_main()