首页 > 解决方案 > 第一年的项目:我的 while 循环中的一个小错误让我发疯。非常感谢任何帮助

问题描述

这段代码的目标是开发一个调度程序,它首先处理最短的工作。我得到了一个process object由 w/ 发起的arrival time, a completion time, and a process ID number。计时器随着每个循环递增。

idle如果计时器未达到到达时间,程序应继续运行。

如果一个进程有arrived (arrival >= timer),程序将循环完成时间所需的次数。

如果有多个进程arrived,我应该先完成最短的工作。

我现在的问题是我所有的偷看和删除都包含在我的while not process_queue.is_empty():

但是我仍然以错误告终,因为在队列变空后,我尝试查看一个空队列。

考虑到我的 while 循环条件,我对为什么以及如何能够窥视一个空队列感到困惑。


    def schedule_SJF(processes):
        """
            -------------------------------------------------------
            Description:
                Creates a schedule and an elapsed time to complete all processes using SJF implementation.
                (if >1 process has arrived, the one with the shortest completion time takes priority.)
            Use: schedule_SJF(processes)
            -------------------------------------------------------
            Parameters:
                processes - a list of Process objects pulled from a file (list) (from: processes = read_processes(filename))
            Returns:
                None            
            -------------------------------------------------------
            """
        timer = 0
        buffer = []
        length = len(processes)
        process_queue = pQueue(length, 'L')
        # initialize counter (timer), initialize temporary list to store all arrived processes (buffer),
        # initialize variable for length & initialize pQueue with 'L' mode and .

    print('Scheduling processes1.txt')
    # starting statement

    for i in processes:
        process_queue.insert(i)
    # input all data into a queue for easy use

    while not process_queue.is_empty():
        # loop until queue is empty

        if timer == 0:
            print('[Timer: 0]: Starting SJF Scheduler')
            timer += 1
        # for program start up

        elif not process_queue.is_empty() and process_queue.peek().arrival <= timer:
        # we now know >= 1 process has arrived

            while not process_queue.peek().arrival > timer:           
                buffer.append(process_queue.peek())
                process_queue.remove()    
            # create a list containing all arrived processes, break when arrival time becomes greater than the timer

            while not len(buffer) == 0 :
                shortest = buffer[0]
            # loop until buffer is empty & initialize value for shortest

                for i in range(len(buffer)):                  
                    if buffer[i].time < shortest.time:
                        shortest = buffer[i]
                buffer.remove(shortest)
                # compare all values within the buffer, isolate the value with the shortest time, remove that value.

                print('Fetching Process: {}'.format(shortest))
                for _ in range(shortest.time):
                    print('[Timer:{}]: {}'.format(timer, shortest.PID))
                    timer += 1
                # loop for as many times as is necessary to 'complete' the task

        else:
            print('[Timer:{}]: {}'.format(timer, 'idle'))
            timer += 1
        # if not timer >= arrival, program should continue looping (on 'idle')

    return

标签: python-3.xwhile-loopscheduled-tasksschedulerpriority-queue

解决方案


至于为什么你在窥视一个空队列时会出错,让我们看看你的代码:

    elif not process_queue.is_empty() and process_queue.peek().arrival <= timer:
    # we now know >= 1 process has arrived

        while not process_queue.peek().arrival > timer:           
            buffer.append(process_queue.peek())
            process_queue.remove()    

你的问题是在最后一种while情况。它不检查队列是否为空。当您传递 时,队列不是空的elif,但是 中的代码while会从队列中删除一个项目。想象一下,如果队列包含一个到达时间小于 的单个项目会发生什么timer。执行进入循环体,从队列中删除该项目。然后它回到有条件的并试图偷看。但是队列中什么都没有。

解决方案是在偷看之前检查一个空队列。

你解决这个问题的方法有点令人困惑。你正在做的是,基本上:

Add processes to a queue
while the queue isn't empty
    Remove all the processes from the queue that are earlier than the current time, and put them into a buffer
    while the buffer isn't empty
        find the process with the earliest arrival time, and process it

这看起来像很多不必要的复杂性。

似乎这样做会更容易:

Sort processes by arrival time
Add sorted processes to queue
while queue is not empty
    Extract the next job, and process it

或者,甚至更好:

Add processes to a priority queue (see [heapq][1])
while priority queue is not empty
    Extract the next job, and process it

推荐阅读