我对非阻塞IO的概念还不太熟悉,有一点我很难理解——关于协同程序。考虑以下代码:
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
的值存储在哪里?恢复执行时如何访问它?在
任何帮助都将不胜感激!在
当^{执行时,
var
的内存仍在使用,但是get
函数本身是“冻结”的,这允许其他函数执行。Tornado的协程是使用Python生成器实现的,它允许在yield
发生时暂时中止函数的执行,然后在屈服点之后再次重新启动(保留函数的状态)。以下是在PEP that introduced generators中描述该行为的方式:@gen.coroutine
生成器具有与Tornado的事件循环关联的魔力,因此,insert
调用返回的Future
注册到事件循环中,从而允许在insert
调用完成时重新启动get
生成器。在相关问题 更多 >
编程相关推荐