Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

next是什么时候触发 zombieframe的 #30

Closed
Panlq opened this issue Jul 21, 2020 · 4 comments
Closed

next是什么时候触发 zombieframe的 #30

Panlq opened this issue Jul 21, 2020 · 4 comments
Assignees
Labels
question Further information is requested

Comments

@Panlq
Copy link

Panlq commented Jul 21, 2020

请问:当YIELD VALUE -> POP TOP 推出栈顶元素后,此时中断了,是怎么进入zombie状态的,next调用的时候是怎么触发执行原来的frame的?
我的理解是当pop top 后,此时的PyFrameObject是进入zombie状态了,然后如果是有其他函数就走其他函数。 就您的案例来说,当继续调用next(gg)的时候,是怎么触发 zombie状态的frame的呢?

@Panlq
Copy link
Author

Panlq commented Jul 21, 2020

我的理解是

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

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

@zpoint
Copy link
Owner

zpoint commented Jul 21, 2020

不管是迭代器还是函数, 都有对应的 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 时引入的一个缓存策略, 从这个角度看是和普通函数调用还是迭代器的调用没有关系

@Panlq
Copy link
Author

Panlq commented Jul 21, 2020

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

@zpoint zpoint self-assigned this Jul 21, 2020
@zpoint zpoint added the question Further information is requested label Jul 21, 2020
@zpoint
Copy link
Owner

zpoint commented Jul 21, 2020

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

@zpoint zpoint closed this as completed Jul 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
source-code-notes
Awaiting triage
Development

No branches or pull requests

2 participants