win10 + cygwin + clion
基本实现了书上所有的功能,从零构建一个简单的Python虚拟机。
除了GC还存在一些问题,需要参考作者的新项目HiLang改造为链表记录对象的创建。
对随书源码的几个小问题做了修改,CMakeLists也做了一点调整。
最后一章实现了yield和generator以后,就可以写出一个最简单的协程:
# Two simple generator functionsdefcountdown(n):
whilen>0:
print('T-minus', n)
yieldn-=1print('Blastoff!')
defcountup(n):
x=0whilex<n:
print('Counting up', x)
yieldx+=1classTaskScheduler:
def__init__(self):
self._task_queue= []
defnew_task(self, task):
''' Admit a newly started task to the scheduler '''self._task_queue.append(task)
defrun(self):
''' Run until there are no more tasks '''whilelen(self._task_queue) >0:
task=self._task_queue.popleft()
try:
# Run until the next yield statementtask.next()
self._task_queue.append(task)
exceptStopIteration:
# Generator is no longer executingpass# Example usesched=TaskScheduler()
sched.new_task(countdown(2))
sched.new_task(countup(5))
sched.run()输出结果:
[T-minus, 2]
[Countingup, 0]
[T-minus, 1]
[Countingup, 1]
Blastoff!
[Countingup, 2]
[Countingup, 3]
[Countingup, 4]