龙卷风协程函数中的变量会发生什么? [英] what happens to variables in tornado coroutines functions?
问题描述
我是非阻塞IO概念的新手,在了解协同程序方面有些困难.考虑以下代码:
I'm new to the concept of non-blocking IO, and there is something i'm having trouble understanding - about coroutines. consider this code:
class UserPostHandler(RequestHandler):
@gen.coroutine
def get(self):
var = 'some variable'
data = json.loads(self.request.body)
yield motor_db.users.insert({self.request.remote_ip: data})#asynch non blocking db insert call
#success
self.set_status(201)
print var
当调用get
函数时,它将创建字符串var
.当函数等待motor.insert
完成时,此变量会发生什么?据我了解,非阻塞"表示没有线程在等待IO调用完成,并且在等待时没有使用内存.那么var
的值存储在哪里?恢复执行后如何访问?
when the get
function is called, it creates the string var
. what happens to this variable when the function waits for the motor.insert
to complete? To my understanding "non blocking" implies that no thread is waiting for the IO call to complete, and no memory is being used while waiting. So where is the value of var
stored? how is it accessible when the execution resumes?
任何帮助将不胜感激!
推荐答案
在执行insert
时,仍在使用var
的内存,但是get
函数本身是冻结的",允许其他函数执行执行. Tornado的协程使用Python生成器实现,当yield
发生时,该函数允许函数的执行被暂时挂起,然后在屈服点之后再次重新启动(保留函数的状态). 引入了生成器的PEP 中是这样描述行为的:
The memory for var
is still being used while insert
executes, but the get
function itself is "frozen", which allows other functions to execute. Tornado's coroutines are implemented using Python generators, which allow function execution to be temporarily suspended when a yield
occurs, and then be restarted again (with the function's state preserved) after the yield point. Here's how the behavior is described in the PEP that introduced generators:
如果遇到yield语句,则函数的状态为 冻结,并将值[yielded]返回给.next()的调用方.经过 冻结"是指保留所有本地状态,包括 当前局部变量的绑定,指令指针和 内部评估堆栈:保存了足够的信息,以便 下次调用.next()时,该函数可以完全像 yield语句只是另一个外部调用.
If a yield statement is encountered, the state of the function is frozen, and the value [yielded] is returned to .next()'s caller. By "frozen" we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time .next() is invoked, the function can proceed exactly as if the yield statement were just another external call.
@gen.coroutine
生成器具有与Tornado的事件循环相关联的魔力,因此,由insert
调用返回的Future
被注册到事件循环中,从而允许get
生成器在启动时重新启动. insert
通话完成.
The @gen.coroutine
generator has magic in it that ties into Tornado's event loop, so that the Future
returned by the insert
call is registered with the event loop, allowing the get
generator to be restarted when the insert
call completes.
这篇关于龙卷风协程函数中的变量会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!