【发布时间】:2012-09-25 00:32:55
【问题描述】:
我想实现一个能够在 FIFO 模式和优先级模式下运行的队列。这是一个消息队列,优先级首先取决于消息类型:例如,如果A 类型的消息比B 类型的消息具有更高的优先级,那么所有@ 类型的消息987654323@类型的消息先出队列,最后B类型的消息出队列。
优先模式:我的想法是使用多个队列,每种消息一个队列;通过这种方式,我可以根据消息类型管理优先级:只需先从优先级较高的队列中取出消息,然后再从优先级较低的队列中取出。
先进先出模式:如何处理使用多个队列的先进先出模式?换句话说,用户看不到多个队列,但它使用队列就像它是单个队列一样,以便在禁用优先级模式时消息按照它们到达的顺序离开队列。为了实现第二个目标,我曾考虑使用另一个队列来管理消息类型的到达顺序:让我用下面的代码 sn-p 更好地解释一下。
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;
}
}
}
}
你觉得这个想法怎么样? 有更好或更简单的实现吗?
【问题讨论】:
标签: oop algorithm language-agnostic