【问题标题】:Python performing multiple tasksPython 执行多项任务
【发布时间】:2014-07-06 15:52:13
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 这里的问题在哪里?
  • @Michal 只是想知道我应该使用什么 python 库来实现这一点,我看到多处理无法真正弄清楚如何调用多个函数并获得响应或只是等待第一个回应......希望能给你一些想法,我想要实现的目标。谢谢

标签: python multithreading process parallel-processing multiprocessing


【解决方案1】:

您可以为此使用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()

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

【讨论】:

  • 你如何确保第一个响应取消其他响应?
  • @AustinMullins 见上文。
  • @Eli 适用于我正在尝试做的事情......谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 2016-01-27
  • 2021-08-02
  • 1970-01-01
  • 2017-08-19
相关资源
最近更新 更多