龙卷风协程函数中的变量会发生什么?

2024-10-03 11:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我对非阻塞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的值存储在哪里?恢复执行时如何访问它?在

任何帮助都将不胜感激!在


Tags: 函数代码ioself概念dbdataget
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:32

当^{执行时,var的内存仍在使用,但是get函数本身是“冻结”的,这允许其他函数执行。Tornado的协程是使用Python生成器实现的,它允许在yield发生时暂时中止函数的执行,然后在屈服点之后再次重新启动(保留函数的状态)。以下是在PEP that introduced generators中描述该行为的方式:

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注册到事件循环中,从而允许在insert调用完成时重新启动get生成器。在

相关问题 更多 >