Skip to main content
 首页 » 编程设计

Python 执行多项任务

2024年10月25日10webabcd

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

编辑:为此在多处理中使用队列,因为它是进程安全的。