我的 API 中有一个端点,它实际上从不同的数据源获取数据,我想做的是立即向所有数据源发送请求,一旦我从数据源获得结果,就将结果返回给用户(如果可能的话,终止所有剩余的请求)。
Python中有哪些好的库可以使用? 任何例子都会有很大帮助
谢谢
最佳答案
您可以使用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()
编辑:为此使用多处理中的队列,因为它是进程安全的。
关于Python 执行多个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24597630/