【发布时间】:2010-12-20 19:53:14
【问题描述】:
我正在尝试将同步库转换为使用内部异步 IO 框架。我有几种方法看起来像这样:
def foo:
....
sync_call_1() # synchronous blocking call
....
sync_call_2() # synchronous blocking call
....
return bar
对于每个同步函数 (sync_call_*),我编写了一个相应的异步函数,它接受一个回调。例如
def async_call_1(callback=none):
# do the I/O
callback()
现在对于 python 新手问题 - 将现有方法转换为使用这些新的异步方法的最简单方法是什么?也就是上面的方法foo()现在需要是:
def async_foo(callback):
# Do the foo() stuff using async_call_*
callback()
一个明显的选择是将回调传递给每个异步方法,该方法有效地“恢复”调用“foo”函数,然后在方法的最后调用全局回调。但是,这会使代码变得脆弱、难看,我需要为每次调用 async_call_* 方法添加一个新的回调。
有没有一种简单的方法可以使用 python 习语来做到这一点,例如生成器或协程?
【问题讨论】:
标签: python asynchronous generator