如何异步执行几次函数并得到第一个结果

时间:2015-12-09 05:47:17

标签: python multithreading multiprocessing threadpool

我有一个函数get_data(request),它向服务器请求一些数据。每次调用此函数时,它都会向不同的服务器请求数据。所有这些都应该返回相同的响应。

我想尽快得到答复。我需要创建一个多次调用get_data的函数,并返回它得到的第一个响应。

修改

我提出了使用multithreading.Pipe()的想法,但我觉得这是解决它的一种非常糟糕的方式,你怎么看?:

def get_data(request, pipe):
    data = # makes the request to a server, this can take a random amount of time
    pipe.send(data)

def multiple_requests(request, num_servers):
    my_pipe, his_pipe = multithreading.Pipe()

    for i in range(num_servers):
        Thread(target = get_data, args = (request,his_pipe)).start()

    return my_pipe.recv()

multiple_requests("the_request_string", 6)

我认为这是一种不好的方法,因为你将相同的管道传递给所有线程,我真的不知道,但我想这必须非常不安全。

1 个答案:

答案 0 :(得分:1)

我认为redis rq对它有好处。 get_data是你在队列中放六次的工作。作业执行异步,在文档中你也可以阅读如何操作结果。