Tulip/asyncIO:为什么不是所有的调用都是异步的并指定什么时候应该同步? [英] Tulip/asyncIO: why not all calls be async and specify when things should be synchronous?

查看:22
本文介绍了Tulip/asyncIO:为什么不是所有的调用都是异步的并指定什么时候应该同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 Guido 谈论关于郁金香时,我参加了 SF Python 聚会,用于 Python 中异步操作的未来 asyncIO 库.

I went to the SF Python meetup when Guido talked about Tulip, the future asyncIO library for asynchronous operations in Python.

需要注意的是,如果您想要异步运行某些东西,您可以使用 "yield from" + 表达式 和几个装饰器来指定对 之后的内容的调用yield from 应该异步执行.关于它的好处是您可以正常读取该函数中的语句(就像它是同步的一样),并且它的行为就好像它在该函数的执行方面是同步的(返回值和错误/异常传播和处理)).

The take away is that if you want something to be run asynchronously you can use the "yield from" + expression and a couple of decorators to specify that the call to what comes after yield from should be executed asynchronously. The nice thing about it is that you can read the statements in that function normally (as if it was synchronous) and it will behave as if it was synchronous with respect to the execution of that function (return values and error/exception propagation and handling).

我的问题是:为什么不具有相反的行为,即默认情况下所有函数调用都是异步的(并且没有 yield from)并且在您想要执行某些操作时使用不同的显式语法同步?

My question is: why not have the opposite behavior, namely, have all function calls be by default async (and without the yield from) and have a different explicit syntax when you want to execute something synchronously?

(除了需要另一个关键字/语法规范)

(besides the need for another keyword/syntax spec)

推荐答案

真正的答案是 Guido 喜欢异步屈服点在协程中是明确的,因为如果你没有意识到一个调用可以产生,那么这就是并发问题的邀请——就像线程一样.但是,如果您必须编写一个显式的 yield from,很容易确保它不会出现在两个对其余代码来说应该是原子的关键操作的中间.

The real answer is that Guido likes the fact that asynchronous yield points are explicit in coroutines, because if you don't realize that a call can yield, then that's an invitation to concurrency problems -- like with threads. But if you have to write an explicit yield from, it's fairly easy to make sure it doesn't land in the middle of two critical operations that should appear atomic to the rest of the code.

正如他在他的 PyCon 2013 主题演讲中提到的,还有其他 Python 异步像 Gevent 这样的框架,默认情况下是异步的,他不喜欢这种方法.(在 11:58):

As he mentions in his PyCon 2013 keynote, there are other Python async frameworks like Gevent, which are async by default, and he doesn't like that approach. (at 11:58):

不幸的是你仍然没有完全清除问题调度程序可以在随机时刻中断您的任务和切换到另一个.[...] 你今天调用的任何函数你碰巧知道它永远不会切换,明天有人可以添加日志语句或延迟缓存或设置咨询文件.[...]

And unfortunately you're still not completely clear of the problem that the scheduler could at a random moment interrupt your task and switch to a different one. [...] Any function that you call today that you happen to know that it never switches, tomorrow someone could add a logging statement or a lazy caching or a consulting of a settings file. [...]

这篇关于Tulip/asyncIO:为什么不是所有的调用都是异步的并指定什么时候应该同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆