简体   繁体   English

c ++有序(稳定)优先级队列

[英]c++ ordered(stable) priority queue

I am implementing a toy scheduler which reads a input file of process specifications such as arrival time, total run time and then schedules the process based on random io/cpu bursts. 我正在实现一个玩具调度程序,它读取进程规范的输入文件,如到达时间,总运行时间,然后根据随机io / cpu突发调度进程。

The file is of the format 该文件的格式

Arrival time, total CPU time, CPU burst, IO Burst. 到达时间,总CPU时间,CPU突发,IO突发。

Now, when there are two process with same arrival time, the scheduler have to schedule the process first the process which is mentioned first in the file. 现在,当有两个具有相同到达时间的进程时,调度程序必须首先调度该进程,该进程首先在文件中提到。

I am keeping the entries in the file in a priority queue. 我将文件中的条目保留在优先级队列中。

struct EventComparator{
  bool operator()(const Event* event1, const Event* event2){
    return event1->getTimestamp() >= event2->getTimestamp();
  }   
};  
priority_queue<Event*, vector<Event*>, EventComparator> eventQueue;

where Event is just an object encapsulating the process parameters. 其中Event只是一个封装过程参数的对象。

My problem is, the priority queue is not stable. 我的问题是,优先级队列不稳定。 By stable I mean that the order of the process gets reversed. 稳定我的意思是过程的顺序颠倒过来。

Suppose the input file has 假设输入文件有

60 200 5 20 60 200 5 20

60 20 10 10 60 20 10 10

40 100 10 40 40 100 10 40

0 200 40 90 0 200 40 90

If i pop from the priority queue, I expect Line4, line 3, Line1 and then Line2. 如果我从优先级队列弹出,我期待Line4,第3行,第1行,然后是Line2。 But I get Line4, Line3, Line2, Line1. 但我得到了Line4,Line3,Line2,Line1。

My question is, what can I do to get a stable priority queue? 我的问题是,我该怎么做才能获得稳定的优先级队列?

  1. Your comparator is incorrect. 您的比较器不正确。 The documentation for the std::priority_queue states that it should provide a strict weak ordering(that is, it should event1->getTimestamp() > event2->getTimestamp() , not >= ). std::priority_queue文档声明它应该提供严格的弱排序(即,它应该是event1->getTimestamp() > event2->getTimestamp() ,而不是>= )。

  2. To make it stable, you can just store the line number inside the Event and compare it if event1->getTimestamp() == event2->getTimestamp() . 为了使其稳定,您只需将行号存储在Event ,并在event1->getTimestamp() == event2->getTimestamp()

Something like this: 像这样的东西:

struct EventComparator {
  bool operator()(const Event* event1, const Event* event2) {
    if (event1->getTimestamp() != event2->getTimestamp()) {
      return event1->getTimestamp() > event2->getTimestamp();
    }
    return event1->getLineNumber() > event2->getLineNumber();
  }   
};  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM