Skip to content

Commit

Permalink
bpo-38091: Import deadlock detection causes deadlock (GH-17518)
Browse files Browse the repository at this point in the history
Automerge-Triggered-By: @brettcannon
  • Loading branch information
arigo committed Mar 3, 2020
1 parent ce3a498 commit 6daa37f
Show file tree
Hide file tree
Showing 4 changed files with 1,688 additions and 1,667 deletions.
9 changes: 9 additions & 0 deletions Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,22 @@ def has_deadlock(self):
# Deadlock avoidance for concurrent circular imports.
me = _thread.get_ident()
tid = self.owner
seen = set()
while True:
lock = _blocking_on.get(tid)
if lock is None:
return False
tid = lock.owner
if tid == me:
return True
if tid in seen:
# bpo 38091: the chain of tid's we encounter here
# eventually leads to a fixpoint or a cycle, but
# does not reach 'me'. This means we would not
# actually deadlock. This can happen if other
# threads are at the beginning of acquire() below.
return False
seen.add(tid)

def acquire(self):
"""
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_import/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,16 +436,24 @@ def test_issue31492(self):
os.does_not_exist

def test_concurrency(self):
# bpo 38091: this is a hack to slow down the code that calls
# has_deadlock(); the logic was itself sometimes deadlocking.
def delay_has_deadlock(frame, event, arg):
if event == 'call' and frame.f_code.co_name == 'has_deadlock':
time.sleep(0.1)

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data'))
try:
exc = None
def run():
sys.settrace(delay_has_deadlock)
event.wait()
try:
import package
except BaseException as e:
nonlocal exc
exc = e
sys.settrace(None)

for i in range(10):
event = threading.Event()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Tweak import deadlock detection code to not deadlock itself.
Loading

0 comments on commit 6daa37f

Please sign in to comment.