大致思路:
python 運(yùn)行過(guò)程中會(huì)產(chǎn)生調(diào)用棧,當(dāng)線程死鎖時(shí),棧信息就會(huì)停留在線程死鎖的那一刻,通過(guò)查看此時(shí)的棧信息,就可以找到導(dǎo)致線程死鎖的具體位置。
打印調(diào)用棧的核心代碼如下:
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
這段代碼可以打印出一段可讀性較強(qiáng)的棧信息,只需要再再外層簡(jiǎn)單封裝,令其每隔一段時(shí)間打印并記錄下當(dāng)前棧信息就可以有效定位出線程死鎖的具體位置。