【问题标题】:python multiprocessing pool freezespython多处理池冻结
【发布时间】:2014-08-25 04:24:25
【问题描述】:

使用 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)

当我使用所有 url(可能有 30 个 url)时,它会在运行第一组后冻结。 当我在上面的代码中使用 5 个 url (url[0:4]) 时,它不会冻结。 任何想法为什么? 该代码是测试代码,因此它应该永远运行(几个小时)。

【问题讨论】:

  • 您不应该在 while 循环内重新创建 Pool 对象。在外面创建。

标签: python multiprocessing pool


【解决方案1】:

ops,这个问题与池无关。 这是一些冻结的网址。 我通过添加超时来修复它:

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

还要注意,使用过多的工作人员会导致应用程序由于资源不足而冻结。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2013-05-17
    • 1970-01-01
    • 2018-01-30
    • 2019-08-14
    • 2021-07-24
    • 2020-08-14
    相关资源
    最近更新 更多