Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6daa37f

Browse files
authored
bpo-38091: Import deadlock detection causes deadlock (GH-17518)
Automerge-Triggered-By: @brettcannon
1 parent ce3a498 commit 6daa37f

4 files changed

Lines changed: 1688 additions & 1667 deletions

File tree

Lib/importlib/_bootstrap.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,22 @@ def has_deadlock(self):
6767
# Deadlock avoidance for concurrent circular imports.
6868
me = _thread.get_ident()
6969
tid = self.owner
70+
seen = set()
7071
while True:
7172
lock = _blocking_on.get(tid)
7273
if lock is None:
7374
return False
7475
tid = lock.owner
7576
if tid == me:
7677
return True
78+
if tid in seen:
79+
# bpo 38091: the chain of tid's we encounter here
80+
# eventually leads to a fixpoint or a cycle, but
81+
# does not reach 'me'. This means we would not
82+
# actually deadlock. This can happen if other
83+
# threads are at the beginning of acquire() below.
84+
return False
85+
seen.add(tid)
7786

7887
def acquire(self):
7988
"""

Lib/test/test_import/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,16 +436,24 @@ def test_issue31492(self):
436436
os.does_not_exist
437437

438438
def test_concurrency(self):
439+
# bpo 38091: this is a hack to slow down the code that calls
440+
# has_deadlock(); the logic was itself sometimes deadlocking.
441+
def delay_has_deadlock(frame, event, arg):
442+
if event == 'call' and frame.f_code.co_name == 'has_deadlock':
443+
time.sleep(0.1)
444+
439445
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data'))
440446
try:
441447
exc = None
442448
def run():
449+
sys.settrace(delay_has_deadlock)
443450
event.wait()
444451
try:
445452
import package
446453
except BaseException as e:
447454
nonlocal exc
448455
exc = e
456+
sys.settrace(None)
449457

450458
for i in range(10):
451459
event = threading.Event()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Tweak import deadlock detection code to not deadlock itself.

0 commit comments

Comments
 (0)