Python崩溃的输出原因

我有一个应用程序,每隔几分钟轮询一堆服务器.为此,它为每个服务器生成一个线程进行轮询(15个服务器)并将数据写回到对象:

import requests

class ServerResults(object):
    def __init__(self):
        self.results = []

    def add_server(some_argument):
        self.results.append(some_argument)

servers = ['1.1.1.1','1.1.1.2']
results = ServerResults()

for s in servers:
    t = CallThreads(poll_server,s,results)
    t.daemon = True
    t.start()

def poll_server(server,results):
    response = requests.get(server,timeout=10)
    results.add_server(response.status_code);

CallThreads类是一个调用函数的辅助函数(在本例中是带参数的poll_server()(在本例中是s和结果),你可以看到我的Github repo为Python utility functions的源代码.大多数时候这个工作正常,但是有时一个线程间歇性地挂起.我不知道为什么,因为我在GET请求上使用了超时.无论如何,如果线程挂起,则挂起的线程会在数小时或数天内累积,然后Python崩溃:

  File "/usr/lib/python2.7/threading.py",line 495,in start
    _start_new_thread(self.__bootstrap,())
thread.error: can't start new thread

Exception in thread Thread-575 (most likely raised during interpreter shutdown)
Exception in thread Thread-1671 (most likely raised during interpreter shutdown)
Exception in thread Thread-831 (most likely raised during interpreter shutdown)

我怎么处理这个?似乎没有办法到0781 a blocking thread in Python.这个应用程序需要在Raspberry Pi上运行,所以像twisted这样的大型库不适合,实际上我也需要摆脱requests库!

最佳答案
据我所知,一个可能的情况是当一个线程为一个给定的服务器“挂起”时,它将“永远”停留在那里.下次查询服务器时,会生成另一个线程(_start_new_thread),直到Python崩溃.

可能不是你的(主要)问题,但你应该:

>使用线程池 – 这不会对系统的有限资源施加压力,就像一次又一次地生成新线程一样.
>检查您是否使用“线程兼容”机制来处理对结果的并发访问.也许是semaphoremutex来锁定代码的原子部分.可能更好的是专用数据结构,例如queue.

关于“挂起”本身 – 请注意“打开URL”(urlopen)时的超时参数与建立连接的超时有关.不是为了下载实际数据:

The optional timeout parameter specifies a timeout in seconds for
blocking operations like the connection attempt (if not specified,the
global default timeout setting will be used). This actually only works
for HTTP,HTTPS and FTP connections.

相关文章

使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧...
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行...
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的...
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行...
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的...
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据...