Giter VIP home page Giter VIP logo

Comments (4)

Panlq avatar Panlq commented on May 16, 2024

我的理解是

gg = gen()   # 生成一个生成器对象
next(gg)      # 触发生成器
gg.send()    # 或者调用生成器对象的send唤醒 上一次的 `zombie`状态

调用的对象是的生成器对象,当这个对象被执行的时候,就从zombie frame当时的上下文栈空间继续执行

from cpython-internals.

zpoint avatar zpoint commented on May 16, 2024

不管是迭代器还是函数, 都有对应的 code 对象来表示这段代码中的一些信息

frame 对象是你每次运行这段代码的时候, 解释器自动帮你创建的, 在你结束运行这段代码的时候, 解释器会帮你销毁

zombie frame 是指在销毁的时候检查对应的 code 对象上的 co_zombieframe 字段是否为空, 是的话则不销毁了, 把这个 frame 的地址存储在这里

然后下一次再运行这段代码需要创建新的 frame 对象时, 优先从这里取, 取不到再去创建

这是一个缓存策略

而你上面提到的的迭代器, 和这个策略应该没有关系
通常函数的运行大致过程是:

  1. 创建 frame, 初始化参数等信息
  2. 执行 code 对象里面存储的对应的字节码(从头到尾执行完)
  3. 执行完成, 销毁 frame

迭代器调用时

  1. 函数调用会创建 gen 对象
  2. gen 对象负责 创建 frame, 初始化参数等信息
  3. 你对这个 gen 对象不管是进行 for 循环遍历, 还是调用 gg.send() , 这个 gen 对象都会去执行 code 对象里面存储的对应的字节码
  4. 执行到 yield 语句时, 返回到 gen 对象这里
  5. gen 对象保存当前 frame 的信息(执行到一半的状态), 并返回给调用者, 下一次你再调用还是进入到第 3 步
  6. gen 对象接到了一个 StopIteration 的异常, gen 对象认为调用结束, 此时会负责销毁 frame

zombie frame 是在销毁或者创建 frame 时引入的一个缓存策略, 从这个角度看是和普通函数调用还是迭代器的调用没有关系

from cpython-internals.

Panlq avatar Panlq commented on May 16, 2024

原来如此,谢谢大神指点。
最近有空会学习您的cpython内核文章,我自己会做一些笔记发表博客,博客中有引用的都会加上来源链接,可以?

from cpython-internals.

zpoint avatar zpoint commented on May 16, 2024

可以的, 不是大神哈🤦‍♂️ 一起交流, 互相学习🤝

from cpython-internals.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.