线程内存使用量不断增加

2024-04-26 04:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问网页,并检查网站所有者是否允许与他联系。。在

这是http://pastebin.com/12rLXQaz

这是每个线程调用的函数:

def getpage():
    try:
        curl = urls.pop(0)
        print "working on " +str(curl)
        thepage1 = requests.get(curl).text
        global ctot
        if "Contact Us" in thepage1:
            slist.write("\n" +curl)
            ctot = ctot + 1
    except:
        pass
    finally:
        if len(urls)>0 :
            getpage()  

但问题是程序的内存不断增加。。(pythonw.exe)在

当线程再次调用函数时,条件为真。。程序的内存至少应该保持在相同的水平。在

对于一个包含大约10万个网址的列表,程序占用的空间远远超过3GB,而且还在增加。。。在


Tags: 函数内存程序comhttp网页if网站
2条回答

我看过你的代码:http://pastebin.com/J4Rd3NhA

我会在运行100个线程时使用join:

for xd in range(0,noofthreads):
    t = threading.Thread(target=getpage)
    t.daemon = True
    t.start()
    tarray.append(t)
    # my additional code
    if len(tarray) >= 100:
        tarray[-100].join()

这是如何表现的?如果有什么不对劲,告诉我。在

你的程序是递归的。递归意味着,对于你得到的每一个页面,你都会创建一组新的变量,由于这些变量仍然被函数中的局部变量引用,因为函数永远不会结束,垃圾回收永远也不会起作用,它将继续永远占用内存。在

仔细阅读一下^{}语句,这里要用它代替递归。在

while len(urls)>0 :
    try:
        curl = urls.pop(0)
        thepage1 = requests.get(curl).text
        global ctot
        if "Contact Us" in thepage1:
            slist.write("\n" +curl)
            ctot = ctot + 1
    except:
        pass

相关问题 更多 >