协程模仿操作系统的调度程序

时间:2018-11-04 10:15:01

标签: python-3.x

我正在关注:协程和并发性好奇课程,学习协程,遇到问题使以下代码运行:

该代码模仿操作系统来安排任务

from queue import Quue
class Task:
    taskid = 0

    def __init__(self, target):
        Task.taskid += 1 #count the task
        self.tid = Task.taskid
        self.tartet = target
        self.sendval = None 

    def run(self):
        return self.target.send(self.sendval)

class Scheduler:
    def __init__(self):
        self.ready = Queue() # a queue of tasks that are ready to run.
        self.taskmap = {} #dictionary that keeps track of all active tasks (each task has a unique integer task ID)

    def new(self, target): #introduce a new task to the scheduler
        newtask = Task(target)
        self.taskmap[newtask.tid] = newtask

    def schedule(self, task):
        self.ready.put(task)

    def mainloop(self):
        while self.taskmap: #I think the problem is here
            task = self.ready.get() #I think it should be while self.ready
            result = task.run()
            self.schedule(task)

进行测试
def foo():
    while True:
        print("I'm foo")
        yield

def bar():
    while True:
        print("I'm bar")
        yield

它正在等待而不是返回值

In [85]: schedule.new(foo())                                                                                      

In [86]: schedule.new(bar())                                                                                      

In [87]: schedule.mainloop()                                                                                      






^C---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)

我查看了代码,发现

有问题
def mainloop(self):
    while self.taskmap: #I think the problem is here
        task = self.ready.get() #I think it should be while self.ready
        result = task.run()
        self.schedule(task)

while self.taskmap,但是没有删除元素的方法,因此这是一个无限循环

我将其更改为

def mainloop(self):
    while self.taskmap: #I think the problem is here
        task = self.ready.get() #I think it should be while self.ready
        result = task.run()
        self.schedule(task)

但是,它仍然无法正常工作。

我的代码有什么问题。

0 个答案:

没有答案