Python执行多个任务

2 投票
1 回答
1052 浏览
提问于 2025-04-18 12:16

我在我的API里有一个接口,这个接口实际上是从不同的数据源获取数据。我想做的是一次性向所有的数据源发送请求,一旦从某个数据源得到了结果,就立刻把结果返回给用户(如果可能的话,终止其他的请求)。

在Python中,有哪些好的库可以用来实现这个功能呢?如果能给个例子就更好了。

谢谢!

1 个回答

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()

补充说明:使用Multiprocessing中的队列(Queue)来处理这个问题,因为它是安全的,可以在多个进程中使用。

撰写回答