python - 限制 python 脚本的线程数

标签 python multithreading resources runtime limit

我在 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/

相关文章:

c# - 使用应用程序其他类的 "FindResource"

python - 从数据存储中获取一个随机实体

c# - 使用列表作为线程启动例程的参数时出现索引超出范围错误

c++ - 几个单例 : one for each task

c# - Winforms 应用程序中的可怕 "Callback chains"

servlets - 在基于 servlet 的应用程序中放置以及如何读取配置资源文件?

android - 新 Activity 、选项卡、新应用程序 : when using which

python - 将数据放在特定形状的列表中

python - 对由 Sympy 符号组成的 Dataframe 列进行排序

python - 如何计算 Python 中一批代码的执行时间?