如何使队列从FIFO模式切换到优先级模式



我想实现一个能够在FIFO模式和优先级模式下操作的队列。这是一个消息队列,优先级首先基于消息类型:例如,如果A类型的消息比B类型的消息具有更高的优先级,则所有A类型的消息首先被出列,最后B类型的消息被出列。

优先级模式:我的想法包括使用多个队列,每种消息类型一个队列;通过这种方式,我可以根据消息类型管理优先级:只需首先从优先级较高的队列中获取消息,然后从优先级较低的队列中逐步获取消息。

FIFO模式:如何使用多个队列处理FIFO模式?换言之,用户看不到多个队列,但它将队列当作一个队列来使用,这样当优先级模式被禁用时,消息就会按照到达的顺序离开队列。为了实现第二个目标,我考虑使用另一个队列来管理消息类型的到达顺序:让我用下面的代码片段更好地解释一下。

int NUMBER_OF_MESSAGE_TYPES = 4;
int CAPACITY = 50;
Queue[] internalQueues = new Queue[NUMBER_OF_MESSAGE_TYPES];
Queue<int> queueIndexes = new Queue<int>(CAPACITY);
void Enqueue(object message)
{
int index = ... // the destination queue (ie its index) is chosen according to the type of message.
internalQueues[index].Enqueue(message);
queueIndexes.Enqueue(index);
}
object Dequeue()
{
if (fifo_mode_enabled)
{
// What is the next type that has been enqueued?
int index = queueIndexes.Dequeue();
return internalQueues[index].Dequeue();
}
if (priority_mode_enabled)
{
for(int i=0; i < NUMBER_OF_MESSAGE_TYPES; i++)
{
int currentQueueIndex = i;
if (!internalQueues[currentQueueIndex].IsEmpty())
{
object result = internalQueues[currentQueueIndex].Dequeue();
// The following statement is fundamental to a subsequent switching
// from priority mode to FIFO mode: the messages that have not been
// dequeued (since they had lower priority) remain in the order in
// which they were queued.
queueIndexes.RemoveFirstOccurrence(currentQueueIndex);
return result;
}
}
}
}

你觉得这个主意怎么样?有更好或更简单的实现吗?

应该可以。然而,乍一看,我的想法是

a) 线程不安全,为此需要做大量工作。b) 非异常安全-即排队中的异常或取消排队可能会留下不一致的状态-可能不是问题,例如,如果异常是致命的,但可能是致命的。c) 可能过于复杂和脆弱,尽管我不知道它使用的上下文。

就我个人而言,除非我已经分析过并显示出有性能问题,否则我会有一个"容器",优先级模式会遍历容器,寻找下一个最高优先级的消息——毕竟只有50条消息。我几乎肯定会使用链接列表。我的下一个优化是让一个容器将每个消息类型的第一个指针指向该容器,并在消息出队列时更新指针。

最新更新