Python 中的异步方法调用?

新手上路,请多包涵

我想知道 Python 中是否有任何用于异步方法调用的库。如果你能做类似的事情那就太好了

@async
def longComputation():
    <code>

token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
    doSomethingElse()
    if token.finished():
        result = token.result()

或者异步调用非异步例程

def longComputation()
    <code>

token = asynccall(longComputation())

如果在语言核心中有一个更完善的策略作为本地语言,那就太好了。考虑过这个吗?

原文由 Stefano Borini 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
2 个回答

您可以使用 Python 2.6 中添加的 多处理模块。您可以使用进程池,然后通过以下方式异步获取结果:

 apply_async(func[, args[, kwds[, callback]]])

例如:

 from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

这只是一种选择。这个模块提供了很多工具来实现你想要的。从中制作装饰器也非常容易。

原文由 Lucas S. 发布,翻译遵循 CC BY-SA 2.5 许可协议

就像是:

 import threading

thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # Will run "foo"
....
thr.is_alive() # Will return whether foo is running currently
....
thr.join() # Will wait till "foo" is done

有关详细信息,请参阅 https://docs.python.org/library/threading.html 上的文档。

原文由 Drakosha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题