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 | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 14 | from test.support import verbose, import_module, run_unittest, TESTFN |
Victor Stinner | 45df820 | 2010-04-28 22:31:17 +0000 | [diff] [blame] | 15 | thread = import_module('_thread') |
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: |
| 33 | done_tasks.append(thread.get_ident()) |
| 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 |
| 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 | |
| 77 | class 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 Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 85 | class ThreadedImportTests(unittest.TestCase): |
| 86 | |
Antoine Pitrou | 448acd0 | 2010-07-16 19:10:38 +0000 | [diff] [blame] | 87 | 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 Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 97 | def check_parallel_module_init(self): |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 98 | 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 | |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 102 | done = threading.Event() |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 103 | for N in (20, 50) * 3: |
| 104 | if verbose: |
| 105 | print("Trying", N, "threads ...", end=' ') |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 106 | # Make sure that random and modulefinder get reimported freshly |
| 107 | for modname in ['random', 'modulefinder']: |
| 108 | try: |
| 109 | del sys.modules[modname] |
| 110 | except KeyError: |
| 111 | pass |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 112 | errors = [] |
| 113 | done_tasks = [] |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 114 | done.clear() |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 115 | for i in range(N): |
| 116 | thread.start_new_thread(task, (N, done, done_tasks, errors,)) |
Antoine Pitrou | a62cbf7 | 2010-10-13 23:48:39 +0000 | [diff] [blame] | 117 | done.wait(60) |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 118 | self.assertFalse(errors) |
| 119 | if verbose: |
| 120 | print("OK.") |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 121 | |
Antoine Pitrou | 7224d07 | 2010-08-22 10:18:36 +0000 | [diff] [blame] | 122 | def test_parallel_module_init(self): |
| 123 | self.check_parallel_module_init() |
| 124 | |
| 125 | def test_parallel_meta_path(self): |
| 126 | finder = Finder() |
| 127 | sys.meta_path.append(finder) |
| 128 | try: |
| 129 | self.check_parallel_module_init() |
| 130 | self.assertGreater(finder.numcalls, 0) |
| 131 | self.assertEqual(finder.x, finder.numcalls) |
| 132 | finally: |
| 133 | sys.meta_path.remove(finder) |
| 134 | |
| 135 | def test_parallel_path_hooks(self): |
| 136 | # Here the Finder instance is only used to check concurrent calls |
| 137 | # to path_hook(). |
| 138 | finder = Finder() |
| 139 | # In order for our path hook to be called at each import, we need |
| 140 | # to flush the path_importer_cache, which we do by registering a |
| 141 | # dedicated meta_path entry. |
| 142 | flushing_finder = FlushingFinder() |
| 143 | def path_hook(path): |
| 144 | finder.find_module('') |
| 145 | raise ImportError |
| 146 | sys.path_hooks.append(path_hook) |
| 147 | sys.meta_path.append(flushing_finder) |
| 148 | try: |
| 149 | # Flush the cache a first time |
| 150 | flushing_finder.find_module('') |
| 151 | numtests = self.check_parallel_module_init() |
| 152 | self.assertGreater(finder.numcalls, 0) |
| 153 | self.assertEqual(finder.x, finder.numcalls) |
| 154 | finally: |
| 155 | sys.meta_path.remove(flushing_finder) |
| 156 | sys.path_hooks.remove(path_hook) |
| 157 | |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 158 | def test_import_hangers(self): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 159 | # In case this test is run again, make sure the helper module |
| 160 | # gets loaded from scratch again. |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 161 | try: |
| 162 | del sys.modules['test.threaded_import_hangers'] |
| 163 | except KeyError: |
| 164 | pass |
| 165 | import test.threaded_import_hangers |
| 166 | self.assertFalse(test.threaded_import_hangers.errors) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 167 | |
Antoine Pitrou | 0723d2c | 2010-08-22 20:43:26 +0000 | [diff] [blame] | 168 | def test_circular_imports(self): |
| 169 | # The goal of this test is to exercise implementations of the import |
| 170 | # lock which use a per-module lock, rather than a global lock. |
| 171 | # In these implementations, there is a possible deadlock with |
| 172 | # circular imports, for example: |
| 173 | # - thread 1 imports A (grabbing the lock for A) which imports B |
| 174 | # - thread 2 imports B (grabbing the lock for B) which imports A |
| 175 | # Such implementations should be able to detect such situations and |
| 176 | # resolve them one way or the other, without freezing. |
| 177 | # NOTE: our test constructs a slightly less trivial import cycle, |
| 178 | # in order to better stress the deadlock avoidance mechanism. |
| 179 | delay = 0.5 |
| 180 | os.mkdir(TESTFN) |
| 181 | self.addCleanup(shutil.rmtree, TESTFN) |
| 182 | sys.path.insert(0, TESTFN) |
| 183 | self.addCleanup(sys.path.remove, TESTFN) |
| 184 | for name, contents in circular_imports_modules.items(): |
| 185 | contents = contents % {'delay': delay} |
| 186 | with open(os.path.join(TESTFN, name + ".py"), "wb") as f: |
| 187 | f.write(contents.encode('utf-8')) |
| 188 | self.addCleanup(sys.modules.pop, name, None) |
| 189 | |
| 190 | results = [] |
| 191 | def import_ab(): |
| 192 | import A |
| 193 | results.append(getattr(A, 'x', None)) |
| 194 | def import_ba(): |
| 195 | import B |
| 196 | results.append(getattr(B, 'x', None)) |
| 197 | t1 = threading.Thread(target=import_ab) |
| 198 | t2 = threading.Thread(target=import_ba) |
| 199 | t1.start() |
| 200 | t2.start() |
| 201 | t1.join() |
| 202 | t2.join() |
| 203 | self.assertEqual(set(results), {'a', 'b'}) |
| 204 | |
Tim Peters | aa22223 | 2001-05-22 09:34:27 +0000 | [diff] [blame] | 205 | |
Antoine Pitrou | 1f9dea0 | 2010-07-14 11:52:38 +0000 | [diff] [blame] | 206 | def test_main(): |
| 207 | run_unittest(ThreadedImportTests) |
Tim Peters | 6923234 | 2001-08-30 05:16:13 +0000 | [diff] [blame] | 208 | |
Tim Peters | d974221 | 2001-05-22 18:28:25 +0000 | [diff] [blame] | 209 | if __name__ == "__main__": |
| 210 | test_main() |