Python 中如何利用 decorator 实现异步?

2014-08-10 10:50:15 +08:00
 kzing
在 coolshell [1]看到一段代码, 非常酷:

def async(fn):
@wraps(fn)
def async_func(*args, **kwargs):
_func = Thread(target=fn, args=args, kwargs=kwargs)
_func.start()
return _func
return async_func

@async
def print_data():
pass

def main():
print_data()

可以看到在用 async 装饰之后, 在 main 中是异步调用 print_data.

1. 这是什么原理呢?
2. 还有更强大的方法实现异步吗?


---------
[1]: http://coolshell.cn/articles/11265.html
3135 次点击
所在节点    Python
8 条回复
kier
2014-08-10 10:56:25 +08:00
这个不就是将函数放到单独的线程执行么?
async这个decorator只不过是吧线程的操作独立出来,就不用在每个function里面都去重复这段代码而已,没什么特别
ddzz
2014-08-10 11:47:13 +08:00
要想酷,玩ruby
bcxx
2014-08-10 11:51:28 +08:00
最直接的方法就是用楼主你提到的方案,把要执行的操作放到另外一个 thread 里面做。

用 decorator 的意图就和 @kier 说的一样,为了复用而已(不要把这个模式和要做的东西混淆噢)


然后想更舒服一点的还可以用 work queue (例如 rq 之流)、gevent spawn 之类的。
hahastudio
2014-08-10 11:55:54 +08:00
Python 的 decorator 非常强大,你可以给函数包装出各种附加功能,比如这里有一堆的样例= =
https://wiki.python.org/moin/PythonDecoratorLibrary
zenliver
2014-08-10 13:46:28 +08:00
看看tornado coroutine的实现呗
P9
2014-08-10 14:21:13 +08:00
Python cookbook 第三版 function --- 7.11. Inlining Callback Functions

https://glyph.twistedmatrix.com/2014/02/unyielding.html
《Don't use threads》 此文很长,tornado coroutine 的实现是学习了
https://twistedmatrix.com/documents/13.1.0/api/twisted.internet.defer.html#inlineCallbacks
clino
2014-08-10 14:24:22 +08:00
'还有更强大的方法实现异步吗?'
觉得还是协程好,如gevent
kzing
2014-08-10 20:50:05 +08:00
@hahastudio
@clino
@zenliver
@P9
谢谢: )

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/127030

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX