Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 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 | |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 8 | import os |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 9 | import imp |
| 10 | import sys |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 11 | import time |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 12 | import shutil |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 13 | import unittest |
Antoine Pitrou | 075050f | 2011-07-15 23:09:13 +0200 | [diff] [blame] | 14 | from test.support import ( |
Antoine Pitrou | 314a16b | 2012-05-17 21:02:54 +0200 | [diff] [blame] | 15 | verbose, import_module, run_unittest, TESTFN, reap_threads, forget, unlink) |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 16 | threading = import_module('threading') |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 17 | |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 18 | def task(N, done, done_tasks, errors): |
| 19 | try: |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 20 | # 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 Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 28 | # 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: |
Victor Stinner | 2a12974 | 2011-05-30 23:02:52 +0200 | [diff] [blame] | 33 | done_tasks.append(threading.get_ident()) |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 34 | finished = len(done_tasks) == N |
| 35 | if finished: |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 36 | done.set() |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 37 | |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 38 | # Create a circular import structure: A -> C -> B -> D -> A |
| 39 | # NOTE: `time` is already loaded and therefore doesn't threaten to deadlock. |
| 40 | |
| 41 | circular_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 Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 57 | |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 58 | class 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 |
Antoine Pitrou | 075050f | 2011-07-15 23:09:13 +0200 | [diff] [blame] | 65 | self.lock = threading.Lock() |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 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. |
Antoine Pitrou | 202b606 | 2012-12-18 22:18:17 +0100 | [diff] [blame] | 71 | assert imp.lock_held() |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 72 | with self.lock: |
| 73 | self.numcalls += 1 |
| 74 | x = self.x |
Antoine Pitrou | e0b1c23 | 2012-12-18 23:03:42 +0100 | [diff] [blame^] | 75 | time.sleep(0.01) |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 76 | self.x = x + 1 |
| 77 | |
| 78 | class FlushingFinder: |
| 79 | """A dummy finder which flushes sys.path_importer_cache when it gets |
| 80 | called.""" |
| 81 | |
| 82 | def find_module(self, name, path=None): |
| 83 | sys.path_importer_cache.clear() |
| 84 | |
| 85 | |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 86 | class ThreadedImportTests(unittest.TestCase): |
| 87 | |
Antoine Pitrou | 448acd0 | 2010-07-16 19:10:38 +0000 | [diff] [blame] | 88 | def setUp(self): |
| 89 | self.old_random = sys.modules.pop('random', None) |
| 90 | |
| 91 | def tearDown(self): |
| 92 | # If the `random` module was already initialized, we restore the |
| 93 | # old module at the end so that pickling tests don't fail. |
| 94 | # See http://bugs.python.org/issue3657#msg110461 |
| 95 | if self.old_random is not None: |
| 96 | sys.modules['random'] = self.old_random |
| 97 | |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 98 | def check_parallel_module_init(self): |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 99 | if imp.lock_held(): |
| 100 | # This triggers on, e.g., from test import autotest. |
| 101 | raise unittest.SkipTest("can't run when import lock is held") |
| 102 | |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 103 | done = threading.Event() |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 104 | for N in (20, 50) * 3: |
| 105 | if verbose: |
| 106 | print("Trying", N, "threads ...", end=' ') |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 107 | # 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 Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 113 | errors = [] |
| 114 | done_tasks = [] |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 115 | done.clear() |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 116 | for i in range(N): |
Antoine Pitrou | 075050f | 2011-07-15 23:09:13 +0200 | [diff] [blame] | 117 | t = threading.Thread(target=task, |
| 118 | args=(N, done, done_tasks, errors,)) |
| 119 | t.start() |
Antoine Pitrou | e0b1c23 | 2012-12-18 23:03:42 +0100 | [diff] [blame^] | 120 | self.assertTrue(done.wait(60)) |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 121 | self.assertFalse(errors) |
| 122 | if verbose: |
| 123 | print("OK.") |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 124 | |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 125 | def test_parallel_module_init(self): |
| 126 | self.check_parallel_module_init() |
| 127 | |
| 128 | def test_parallel_meta_path(self): |
| 129 | finder = Finder() |
Brett Cannon | 3c6ea1c | 2012-04-27 13:52:55 -0400 | [diff] [blame] | 130 | sys.meta_path.insert(0, finder) |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 131 | try: |
| 132 | self.check_parallel_module_init() |
| 133 | self.assertGreater(finder.numcalls, 0) |
| 134 | self.assertEqual(finder.x, finder.numcalls) |
| 135 | finally: |
| 136 | sys.meta_path.remove(finder) |
| 137 | |
| 138 | def test_parallel_path_hooks(self): |
| 139 | # Here the Finder instance is only used to check concurrent calls |
| 140 | # to path_hook(). |
| 141 | finder = Finder() |
| 142 | # In order for our path hook to be called at each import, we need |
| 143 | # to flush the path_importer_cache, which we do by registering a |
| 144 | # dedicated meta_path entry. |
| 145 | flushing_finder = FlushingFinder() |
| 146 | def path_hook(path): |
| 147 | finder.find_module('') |
| 148 | raise ImportError |
Brett Cannon | 8923a4d | 2012-04-24 22:03:46 -0400 | [diff] [blame] | 149 | sys.path_hooks.insert(0, path_hook) |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 150 | sys.meta_path.append(flushing_finder) |
| 151 | try: |
| 152 | # Flush the cache a first time |
| 153 | flushing_finder.find_module('') |
| 154 | numtests = self.check_parallel_module_init() |
| 155 | self.assertGreater(finder.numcalls, 0) |
| 156 | self.assertEqual(finder.x, finder.numcalls) |
| 157 | finally: |
| 158 | sys.meta_path.remove(flushing_finder) |
| 159 | sys.path_hooks.remove(path_hook) |
| 160 | |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 161 | def test_import_hangers(self): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 162 | # In case this test is run again, make sure the helper module |
| 163 | # gets loaded from scratch again. |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 164 | try: |
| 165 | del sys.modules['test.threaded_import_hangers'] |
| 166 | except KeyError: |
| 167 | pass |
| 168 | import test.threaded_import_hangers |
| 169 | self.assertFalse(test.threaded_import_hangers.errors) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 170 | |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 171 | def test_circular_imports(self): |
| 172 | # The goal of this test is to exercise implementations of the import |
| 173 | # lock which use a per-module lock, rather than a global lock. |
| 174 | # In these implementations, there is a possible deadlock with |
| 175 | # circular imports, for example: |
| 176 | # - thread 1 imports A (grabbing the lock for A) which imports B |
| 177 | # - thread 2 imports B (grabbing the lock for B) which imports A |
| 178 | # Such implementations should be able to detect such situations and |
| 179 | # resolve them one way or the other, without freezing. |
| 180 | # NOTE: our test constructs a slightly less trivial import cycle, |
| 181 | # in order to better stress the deadlock avoidance mechanism. |
| 182 | delay = 0.5 |
| 183 | os.mkdir(TESTFN) |
| 184 | self.addCleanup(shutil.rmtree, TESTFN) |
| 185 | sys.path.insert(0, TESTFN) |
| 186 | self.addCleanup(sys.path.remove, TESTFN) |
| 187 | for name, contents in circular_imports_modules.items(): |
| 188 | contents = contents % {'delay': delay} |
| 189 | with open(os.path.join(TESTFN, name + ".py"), "wb") as f: |
| 190 | f.write(contents.encode('utf-8')) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 191 | self.addCleanup(forget, name) |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 192 | |
| 193 | results = [] |
| 194 | def import_ab(): |
| 195 | import A |
| 196 | results.append(getattr(A, 'x', None)) |
| 197 | def import_ba(): |
| 198 | import B |
| 199 | results.append(getattr(B, 'x', None)) |
| 200 | t1 = threading.Thread(target=import_ab) |
| 201 | t2 = threading.Thread(target=import_ba) |
| 202 | t1.start() |
| 203 | t2.start() |
| 204 | t1.join() |
| 205 | t2.join() |
| 206 | self.assertEqual(set(results), {'a', 'b'}) |
| 207 | |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 208 | def test_side_effect_import(self): |
| 209 | code = """if 1: |
| 210 | import threading |
| 211 | def target(): |
| 212 | import random |
| 213 | t = threading.Thread(target=target) |
| 214 | t.start() |
| 215 | t.join()""" |
| 216 | sys.path.insert(0, os.curdir) |
| 217 | self.addCleanup(sys.path.remove, os.curdir) |
Antoine Pitrou | 314a16b | 2012-05-17 21:02:54 +0200 | [diff] [blame] | 218 | filename = TESTFN + ".py" |
| 219 | with open(filename, "wb") as f: |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 220 | f.write(code.encode('utf-8')) |
Antoine Pitrou | 314a16b | 2012-05-17 21:02:54 +0200 | [diff] [blame] | 221 | self.addCleanup(unlink, filename) |
Antoine Pitrou | ea3eb88 | 2012-05-17 18:55:59 +0200 | [diff] [blame] | 222 | self.addCleanup(forget, TESTFN) |
| 223 | __import__(TESTFN) |
| 224 | |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 225 | |
Antoine Pitrou | 075050f | 2011-07-15 23:09:13 +0200 | [diff] [blame] | 226 | @reap_threads |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 227 | def test_main(): |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 228 | old_switchinterval = None |
| 229 | try: |
| 230 | old_switchinterval = sys.getswitchinterval() |
Stefan Krah | 219c7b9 | 2012-10-01 23:21:45 +0200 | [diff] [blame] | 231 | sys.setswitchinterval(1e-5) |
Antoine Pitrou | 4f0338c | 2012-08-28 00:24:52 +0200 | [diff] [blame] | 232 | except AttributeError: |
| 233 | pass |
| 234 | try: |
| 235 | run_unittest(ThreadedImportTests) |
| 236 | finally: |
| 237 | if old_switchinterval is not None: |
| 238 | sys.setswitchinterval(old_switchinterval) |
Tim Peters | 6923234 | 2001-08-30 05:16:13 +0000 | [diff] [blame] | 239 | |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 240 | if __name__ == "__main__": |
| 241 | test_main() |