Python多进程池冻结

-2 投票
1 回答
922 浏览
提问于 2025-04-18 12:03

我在用 Python 2.7 写代码,代码如下:

import urllib2
import time
import os
import sys
import multiprocessing
from multiprocessing import Pool
WORKER_COUNT = 10

def worker(url):
    print url
    try:
        response = urllib2.urlopen(url)
        html = response.read()
    except Exception as ex:
        pass

if __name__ == "__main__":
    urls = [
        'http://localhost:90/',
        'http://localhost:90/Default.aspx',
        'http://localhost:91/?a=2&m=0',
        'http://localhost:91/?a=2&m=1',
        'http://localhost:91/?a=2&m=2',
        'http://localhost:91/?s=2',
        'http://localhost:91/?a=2&ft=false',
        'http://localhost:91/?a=2&f=false',
        'http://localhost:91/?fail=1',
        'http://localhost:91/?fail=query',
        'http://localhost:92/?a=2&m=0',
        'http://localhost:92/?a=2&m=1',
        'http://localhost:92/?a=2&m=2',
        'http://localhost:92/?s=2'
        ]
    while True:
        p = Pool(WORKER_COUNT)
        p.map(worker, urls[0:4])# too many urls will cause it to freeze up
        print "Restart"
        time.sleep(5)

当我使用所有的链接(可能有30个链接)时,程序在处理完第一组链接后就卡住了。可是当我只用5个链接(像上面的代码那样,url[0:4])时,程序就不会卡住。你们觉得这是为什么呢?这段代码是测试用的,所以应该可以一直运行下去(几个小时)。

1 个回答

0

哦,这个问题其实和池子没有关系。是某些网址导致了程序卡住。我通过添加一个超时设置来解决这个问题:

import socket
try:
    response = urllib2.urlopen(url, timeout=10)
    html = response.read()
except socket.timeout:
    print "timout"
    pass

另外,要注意如果使用的工作线程太多,会因为资源不足而导致应用程序卡住。

撰写回答