Python 执行多个任务

标签 python multithreading process parallel-processing multiprocessing

我的 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/

相关文章:

java - 如何确保线程不会在 Java 中延迟?

java - 获取锁对象线程正在等待

.net - 为什么没有 .NET Community Process?

python - 为什么我的工作线程没有使用python多线程生成

linux - 停止进程及其子进程的文件缓存

process - 什么时候应该使用 OTP 行为而不是 spawn?

Python difflib,获取偏移量

python - 脚本编译后如何在python中重新加载模块?

python - 如何在 Sikuli 中使用 Python OpenCV 函数

python - Colander 和 Cornice 无法正常工作