事件驱动的模拟器中同时发生的事件
events happening at the same time in event-driven simulator
我一直在尝试开发一个简单的事件驱动模拟器,并从这里开始
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;
相关文章:
- 如何在c++中实现处理器调度模拟器
- Android NDK传感器向事件队列报告奇怪的间隔
- 从文本文件中读取时钟时间和事件时间并进行处理
- WMI检测进程创建事件-c++
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 询问在设计我的手臂模拟器功能表示格式1
- 处理闪烁窗口事件
- C++Builder中的OnClick事件签名存在问题
- 跟踪滚动条上的鼠标事件
- 什么是事件表 (wxWidgets)?
- 如何在 MFCaptureEngine 中获取"Camera removed"事件
- 给定顺序中的事件处理
- 在模拟器中使用并集来模拟CPU寄存器有多合适
- 当服务中的事件被触发时,如何将响应从服务发送回客户端?
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL
- 如何创建事件驱动的 SDL2 应用程序
- Windows 进程间同步类似事件?
- 如何从C++端挂接到 QML 项的 onClick 事件
- 事件驱动的模拟器中同时发生的事件