事件驱动的模拟器中同时发生的事件

events happening at the same time in event-driven simulator

本文关键字:事件 模拟器 事件驱动的      更新时间:2023-10-16

我一直在尝试开发一个简单的事件驱动模拟器,并从这里开始

http://stdcxx.apache.org/doc/stdlibug/11-3.html

当我使用带有一些修改的示例时,我遇到了一种情况,即当两个事件(到达、离开)同时发生时(例如在时间单元 5),那么模拟器只是弹出事件队列顶部的任何内容,如下面的代码片段所示。

void simulation::run () {
while (! eventQueue.empty ()) {
event * nextEvent = eventQueue.top ();
eventQueue.pop ();
time = nextEvent->time;
nextEvent->processEvent ();
delete nextEvent;
  }
}

如果两个事件同时发生,我如何强制执行始终在出发事件之前弹出某个事件(到达事件优先)的条件。

任何帮助都非常感谢。

我假设eventQueue具有此处描述的类型(因为这是您问题中链接引用的内容)。从那里,您可以阅读该top()...

返回对队列中具有最高优先级的元素的常量引用

。那pop()...

从队列中删除具有最高优先级的项目。

因此,从您的问题中获取代码,最明显的方法是从队列中取出具有相同时间的所有事件,然后才处理它们:

while (! eventQueue.empty ()) {
  event * ev = eventQueue.top (); // WHY do you have pointers here ?!?!?
  time = ev->time;
  some_container<event *> arrivals, departures;
  // Take out all events that happen "now" from the queue
  while (time == ev->time) {
    eventQueue->pop();
    if (ev->type == ARRIVAL) {
      arrivals.push_back(ev);
    } else {
      departures.push_back(ev);
    }
    ev = eventQueue->top();
  }
  // Process arrivals
  for (event * e : arrivals) {
    e->processEvent();
    delete e; // Again: WTF pointers? raw? NOT a good idea!
  }
  // Process departures
  for (event * e : departures) {
    e->processEvent();
    delete e;
  }
}

但。。。

。这不是在C++处理这个问题的惯用方法。C++中的容器(至少是有序容器)通常有一个模板参数,指定元素的排序方式。std::priority_queue也是如此:

namespace std {
  template <class T,
            class Container = vector<T>,
            class Compare = less<Container::value_type> >
  class priority_queue;
}

因此,这里更好的方法是使用自定义比较函数对象在所有事件之间建立顺序:

// sigh ... pointers ... raw pointers ... just WHY???!?
template<typename Event>
struct less_event_ptr {
  std::less<time_type> time_compare; // time_type hopefully is self-describing ...
  bool operator()(Event * lhs, Event * rhs) const {
    if (time_compare(lhs->time, rhs>-time)) {
      return true;
    }
    if (time_compare(rhs->time, lhs->time)) {
      return false;
    }
    if (lhs->type == ARRIVAL && rhs->type == DEPARTURE) {
      return true;
    }
    return false;
  }
};

请注意,要使这成为订单,您需要确保不会同时有多个到达(或离开)。如果(可能)会出现这种情况,那么你应该(如果你想要一个确定性的模拟)找到事件的其他属性(名称?来源?)来使它们井井有条。

然后,您的eventQueue将被声明为类似

std::priority_queue<event *, std::vector<event *>, less_event_ptr<event>> eventQueue;