队列排序功能排序到错误的队列

时间:2015-04-10 01:38:46

标签: c sorting struct queue

这是我的队列排序功能,其中dispatchlist,realtime和jobqueue都被定义为队列结构

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;
  }
}

这是我对enqueue的实现

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
}

基本上我最初在调度列表中有7个pcbptr,前4个优先级为1,第5个优先级为0,后2个优先级为1.

那么应该发生的事情是pcbs 1,2,3,4,6,7应该被移动到jobqueue,而pcb 5应该被移动到实时。

当我运行程序时,会打印正确的打印行,因此输出,这是预期的:

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。然而,对于pcbs 5,6,7,它被打印3次。

对我来说,似乎只要一个pcb被移入实时队列,每个其他元素也会被移动到实时队列中,即使它不应该。

有人能发现我可能遗失的东西吗?

由于

PS:我有一个侧面问题,我在打印“blah”的while循环中插入了一个usleep(5000),但它似乎根本没有延迟打印,这可能是什么原因?< / p>

1 个答案:

答案 0 :(得分:0)

问题在于如何将元素从一个队列移动到另一个队列。您在队列中插入了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 );
}