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