在多处理的子进程中调用函数

时间:2016-05-11 06:52:07

标签: python multiprocessing

我正在使用多处理库(在python中不是新的,但在多处理中是新的)。似乎我不了解它是如何运作的。

我尝试做的事情:我向服务器发送了大量的http请求,如果收到连接错误,则表示远程服务已关闭,我使用paramiko重新启动它,然后重新发送请求。我使用多处理加载所有可用的处理器,因为大约有70000个请求,使用一个处理器处理它们大约需要24小时。

我的代码:

# Send request here
def send_request(server, url, data, timeout):
try:
    return requests.post(server + url, json=data, timeout=(timeout or 60))
except Exception:
    return None

# Try to get json from response
def do_gw_requests(request, data):
    timeout = 0
    response = send_request(server, request, data, timeout)
    if response is not None:
        response_json = json.loads(response.text)
    else:
        response_json = None
    return response_json

# Function that recall itself if service is down
def safe_build(data):
exception_message = ""
response = {}
try:
    response = do_gw_requests("/rgw_find_route", data)
    if response is None:
        # Function that uses paramiko to start service
        # It will not end until service is up
        start_service()
        while response is None:
            safe_build(data)
    --some other work here--
return response, exception_message

# Multiprocessing lines in main function
pool = Pool(2)
# build_single_route prepares data, calls safe_build once and write logs
result = pool.map_async(build_single_route, args)
pool.close()
pool.join()

我的问题是,如果服务已经在脚本开始时已经关闭(并且可能在服务中断脚本的工作中)我无法获得两个第一个请求的非空响应。脚本启动,发送两个第一个请求(我将它们循环发送两个),发现服务已关闭(响应变为无),重新启动服务,重新发送请求并且似乎一次又一次地获取无(在无限循环中)。如果我删除循环while response is None:,那么前两个请求将处理,就像它们是None一样,其他请求将按预期处理。但我需要每个请求结果,这就是我重新发送错误请求的原因。 因此它一次又一次地回忆起具有相同数据的功能,但没有成功。对我来说这很奇怪。谁能解释一下我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

似乎问题与池工人的行为不符合我的预期。 response是函数的局部变量,因此在第二次调用safe_build后恢复服务后它变为非None,在第一次调用中它仍然是None。 response, _ = safe_build(data)似乎有效。