Python 线程内存使用率不断增加

Python 线程内存使用率不断增加,python,multithreading,memory,Python,Multithreading,Memory,我正在尝试访问这些网页,并检查网站所有者是否允许与他联系 这是 这是每个线程调用的函数: def getpage(): try: curl = urls.pop(0) print "working on " +str(curl) thepage1 = requests.get(curl).text global ctot if "Contact Us" in thepage1: sli

我正在尝试访问这些网页,并检查网站所有者是否允许与他联系

这是

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

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)

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


对于一个包含大约100k个URL的列表,该程序占用的空间远远超过了3GB,并且正在增加…

我查看了您的代码:

我会在运行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

您是否尝试将它们放入
队列。队列
并且只启动100个线程?或者启动最多100个线程,然后开始
join()
尚未尝试排队。。如果我在函数中使用join,程序将等待所有线程完成,这需要更多的时间1。试着在问题中包含代码的相关位。2.您的代码不起作用,“NameError:未定义名称‘tarray’”。啊。。编辑那个。。现在检查:您的
ctot
slist
使用不是线程安全的。您可以将其移动到主线程,.noofthreads=100。同样的情况也会发生。。(记忆逐渐增强)