Python执行多个任务

时间:2014-07-06 15:52:13

标签: python multithreading process parallel-processing multiprocessing

我的API中有一个端点,它实际上从不同的数据源获取数据,我想要做的是立即向所有数据源发送请求,一旦我从一次数据源获得结果,将结果返回给用户(如果可能,终止所有剩余的请求。)

python中有哪些好的库可以使用? 任何例子都会很有帮助

由于

1 个答案:

答案 0 :(得分:2)

您可以使用multiprocessing库:

from multiprocessing import Process, Queue
import time
q = Queue()

def some_func1(arg1, arg2, q):
    #this one will take longer, so we'll kill it after the other finishes
    time.sleep(20)
    q.put('some_func1 finished!')

def some_func2(arg1, arg2, q):
    q.put('some_func2 finished!')

proc1 = Process(target=some_func1,
                           args = ('arga', 'argb', q))
proc2 = Process(target=some_func2,
                           args = ('arg1', 'arg2', q))
proc1.start()
proc2.start()

#this will be the result from the first thread that finishes.
#At this point you can wait for the other threads or kill them, or whatever you want.
result = q.get()
print result
#if you want to kill all the procs now:
proc1.terminate()
proc2.terminate()

编辑:在多处理中使用队列,因为它可以安全处理。

相关问题