我在 CentOS linux 服务器上有一个 python 2.7 脚本,它有一个启动新线程的错误,直到我无法再登录到服务器。
有没有办法告诉 python 运行时不要创建/启动/使用超过 50 个线程(并抛出异常或终止脚本)来防止这个问题,还是我必须自己在脚本中实现这个?
线程通过thread.start_new_thread()
启动。
最佳答案
根据documentation on the python threading
module (较新的线程模块)您可以调用模块上的 active_count()
方法并找出有多少线程正在运行。现在,我了解到您正在使用较低级别的 thread
模块,所以我通过运行对其进行了调查:
import thread
dir(thread)
这产生了列表:
['LockType', '__doc__', '__name__', '__package__', '_count', '_local', 'allocate', 'allocate_lock', 'error', 'exit', 'exit_thread', 'get_ident', 'interrupt_main', 'stack_size', 'start_new', 'start_new_thread']
(我展示它是因为它对于找出模块包含的内容非常有用,特别是在交互式终端中)
您可以看到 thread
模块包含一个 _count
字段,在调用时(例如 thread._count()
)应该返回运行的线程数(您可以检查此值并在超过最大值时引发异常)。
当然,_count
前面的下划线表示该方法是被对待的,有点像私有(private)方法。但是,在 Python 中您仍然可以访问它。
关于python - 限制 python 脚本的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622930/