队列排序函数排序到错误的队列

Queue sorting function sorts to the wrong queue

下面是我的队列排序函数,其中dispatchlist、realtime、jobqueue都定义为一个queue struct

struct Queue {
  pcbptr front;
  pcbptr back;
};
typedef struct Queue queue;

并且 pcbptr 被定义为

struct PCB {
int pid;                        
int arrival_time;   
int time_left;
int priority;
int status;                     
int printers;
int modems;
int scanners;
int cds;
int memory;         //might need a struct for memory block?
struct PCB* next;
struct PCB* prev;
};
typedef struct PCB pcb;
typedef pcb * pcbptr;

现在实际功能

void starthostd(){
  int i=0;
  while(dispatchlist.front != NULL){
    if(dispatchlist.front->priority == 0){
        enqueue(dispatchlist.front, &realtime);
        dispatchlist.front = dispatchlist.front->next;
        printf("the %d pcb was moved to realtime queue\n", i );
    }
    else{
        enqueue(dispatchlist.front, &jobqueue);
        dispatchlist.front = dispatchlist.front->next;
        printf("the %d pcb was moved to job queue\n", i );
    }
    i++;
  }
  while(realtime.front != NULL){
    printf("blah");
    realtime.front = realtime.front->next;
  }
}

下面是我对入队的实现

void enqueue( pcbptr mypcb, queue* queue) {
  if (queue->front == NULL){ //empty
        queue->front = mypcb;
  }
  else{
    queue->back->next = mypcb; 
  }
  queue->back = mypcb; //set this pcb to the end of the queue
}

基本上我dispatchlist里面本来就有7个pcbptr,前4个优先级1,第5个优先级0,最后2个优先级1.

所以应该发生的是 pcbs 1,2,3,4,6,7 应该被移动到 jobqueue,pcb 5 应该被移动到 realtime。

当我 运行 程序时,打印了正确的打印行,所以这是预期的输出:

the 0 pcb was moved to job queue
the 1 pcb was moved to job queue
the 2 pcb was moved to job queue
the 3 pcb was moved to job queue
the 4 pcb was moved to realtime queue
the 5 pcb was moved to job queue 
the 6 pcb was moved to job queue

(我知道上面语句中的数字落后1)

但是,预期的结果应该是 blah 只打印一次,因为实时队列中只有一个 pcb。但是,印刷电路板 5、6、7 打印了 3 次。

在我看来,一旦一个 pcb 被移入实时队列,所有其他元素也被移入实时队列,即使它不应该如此。

谁能发现我可能遗漏了什么?

谢谢

PS:我有一个附带问题,我在打印 "blah" 的 while 循环中插入了一个 usleep(5000),但它似乎根本没有延迟打印,什么可能是这个原因?

问题在于如何将元素从一个队列移动到另一个队列。您在队列中插入 mypcb,但不考虑与其链接的其他元素。所以你有原始列表

job:      1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
realtime: 

然后你想在队列之间移动第五个元素,但你不改变节点之间的链接,所以你得到了这样的东西

job:      1 -> 2 -> 3 -> 4 -> 6 -> 7
realtime: 5 -> 6 -> 7

要解决此问题,您需要更改队列中的链接,我想这会起作用

if(dispatchlist.front->priority == 0){
    pcbptr t = dispatchlist.front;
    dispatchlist.front = dispatchlist.front->next;
    t->next = NULL;
    enqueue(t, &realtime);
    printf("the %d pcb was moved to realtime queue\n", i );
}