大致思路:
python 運行過程中會產生調用棧,當線程死鎖時,棧信息就會停留在線程死鎖的那一刻,通過查看此時的棧信息,就可以找到導致線程死鎖的具體位置。
打印調用棧的核心代碼如下:
def stacktraces(exclude=()):
code = []
current_frames = [(key, value) for key, value in sys._current_frames().items() if key not in exclude]
for threadId, stack in current_frames:
code.append("\n# ThreadID: %s" % threadId)
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
stackinfo = highlight("\n".join(code), PythonLexer(), HtmlFormatter(
full=False,
# style="native",
noclasses=True,
))
return str(datetime.now()) + ('<p>\nthreadnums: %r</p>' % len(current_frames)) + stackinfo
這段代碼可以打印出一段可讀性較強的棧信息,只需要再再外層簡單封裝,令其每隔一段時間打印并記錄下當前棧信息就可以有效定位出線程死鎖的具體位置。