Check fork() in main thread works while a subthread is doing an import
(self)
| 20 | |
| 21 | class ForkTest(ForkWait): |
| 22 | def test_threaded_import_lock_fork(self): |
| 23 | """Check fork() in main thread works while a subthread is doing an import""" |
| 24 | import_started = threading.Event() |
| 25 | fake_module_name = "fake test module" |
| 26 | partial_module = "partial" |
| 27 | complete_module = "complete" |
| 28 | def importer(): |
| 29 | imp.acquire_lock() |
| 30 | sys.modules[fake_module_name] = partial_module |
| 31 | import_started.set() |
| 32 | time.sleep(0.01) # Give the other thread time to try and acquire. |
| 33 | sys.modules[fake_module_name] = complete_module |
| 34 | imp.release_lock() |
| 35 | t = threading.Thread(target=importer) |
| 36 | t.start() |
| 37 | import_started.wait() |
| 38 | exitcode = 42 |
| 39 | pid = os.fork() |
| 40 | try: |
| 41 | # PyOS_BeforeFork should have waited for the import to complete |
| 42 | # before forking, so the child can recreate the import lock |
| 43 | # correctly, but also won't see a partially initialised module |
| 44 | if not pid: |
| 45 | m = __import__(fake_module_name) |
| 46 | if m == complete_module: |
| 47 | os._exit(exitcode) |
| 48 | else: |
| 49 | if support.verbose > 1: |
| 50 | print("Child encountered partial module") |
| 51 | os._exit(1) |
| 52 | else: |
| 53 | t.join() |
| 54 | # Exitcode 1 means the child got a partial module (bad.) No |
| 55 | # exitcode (but a hang, which manifests as 'got pid 0') |
| 56 | # means the child deadlocked (also bad.) |
| 57 | self.wait_impl(pid, exitcode=exitcode) |
| 58 | finally: |
| 59 | try: |
| 60 | os.kill(pid, signal.SIGKILL) |
| 61 | except OSError: |
| 62 | pass |
| 63 | |
| 64 | |
| 65 | def test_nested_import_lock_fork(self): |