在我的基于 gevent 的程序中,我在某个地方有一个线程,它陷入了一个循环,例如:
while True:
gevent.sleep(0)
我怎样才能弄清楚这是哪个线程?是否可以列出(并获取堆栈跟踪)正在运行的线程?
我在我的代码中使用它来跟踪可能阻塞的greenlets。发生这种情况时会引发 NodeTaskTimeout。只需将您的作业包装在 Timeout 中或为它们提供 TimeOut 对象。
with Timeout(90, False):
task_jobs.join()
if task_jobs:
print 'task jobs killed', task_jobs
task_jobs.kill()
if settings.DEBUG:
raise NodeTaskTimeout
如果它挂起/阻塞/花费很长时间,这个打印就完成了任务。特别令人讨厌的是那些相互依赖并导致死锁 job1 /thread -> job2/thread2 -> job3/thread3 和 job/thread3 只有在 job1 完成时才会完成,这永远不会发生,因为 job2 没有完成而 job2 没有因为job3没有完成而完成..你明白了;)
http://www.rfk.id.au/blog/entry/detect-gevent-blocking-with-greenlet-settrace/
但是您还需要将您怀疑“旋转”的代码放入 with 块中。
有一个用于检查块的官方 API,它会查明导致块的确切行,检查代码示例如下:
# gevent 1.3.7
# greenlet 0.4.15
# zope.event 4.4
import gevent
from gevent import config, get_hub
from gevent.events import IEventLoopBlocked
import logging
from pprint import pformat
import time
import zope.event
# initial logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
# setup gevent config
# enable the monitor thread
config.monitor_thread = True
config.max_blocking_time = 4
# start the monitor thread
hub = get_hub()
monitor = hub.start_periodic_monitoring_thread()
# register the event to logging system
def g(event):
log.error('Greenlet: {}, exceed the max blocking time: {}'.format(event.greenlet, event.blocking_time))
log.error(pformat(event.info))
event = IEventLoopBlocked()
zope.event.subscribers.append(g)
# you can also create you own monitoring function
# def check(hub):
# print('< periodic check in monitoring thread >')
#
# monitor.add_monitoring_function(check, 1)
def gl1():
# use time.sleep to trigger block
log.info('block at gl1 for 2 seconds')
time.sleep(2)
log.info('leave gl1 now')
def gl2():
# use time.sleep to trigger block
log.info('block at gl2 for 6 seconds should be detected')
time.sleep(6)
log.info('leave gl2 now')
def gl3():
# gevent.sleep will not block
log.info('gl3 will not block since it use gevent.sleep')
gevent.sleep(8)
log.info('leave gl3 now')
gevent.joinall([
gevent.spawn(gl3),
gevent.spawn(gl1),
gevent.spawn(gl2),
])
我希望它有帮助!