Exercise: Complex Scenarios
Unqueueing Tails
Easy, right? Now we get to the nasty part: Getting tails back out again!
- If there are any Urgent tails, always send them first. (Don't rotate preference.)
- If there are no other tails available, send a Dismissed tail. (Don't rotate preference.)
- Otherwise, look for tails in your preferred priority, IMPORTANT or REQUESTING. If you have one, return it and rotate the preference.
- If there's nothing in your preferred priority, look in the other priority. (Don't rotate preference.)
- If there are no tails at all, return NULL. (Don't rotate preference.)
compareTo()
.
Our programmer used a very simple state machine with just three states:
- STATE_IMPORTANT_FIRST (0) — means we're preferring our first IMPORTANT tail.
- STATE_REQUESTING (1) — means we're preferring a REQUESTING tail.
- STATE_IMPORTANT_SECOND (2) — means we're preferring our second IMPORTANT tail.
int get(TailQueue* tailQueue, Tail* result)
{
if (isSetEmpty(tailQueue->m_queues[TAIL_URGENT]))
return getNextInRotation(tailQueue, result);
return dequeue(tailQueue, TAIL_URGENT, result);
}int getNextInRotation(TailQueue* tailQueue, Tail* result)
{
switch (tailQueue->m_state)
{
case STATE_IMPORTANT_FIRST:
return getTailFromQueue(tailQueue, result,
TAIL_IMPORTANT, TAIL_REQUESTING, STATE_REQUESTING);
case STATE_REQUESTING:
return getTailFromQueue(tailQueue, result, TAIL_REQUESTING,
TAIL_IMPORTANT, STATE_IMPORTANT_SECOND);
case STATE_IMPORTANT_SECOND:
default:
return getTailFromQueue(tailQueue, result, TAIL_IMPORTANT,
TAIL_REQUESTING, STATE_IMPORTANT_FIRST);
}
}
static int getTailFromQueue(TailQueue* tailQueue, Tail* result,
int firstChoice, int secondChoice, int nextState)
{
if (!isSetEmpty(tailQueue->m_queues[firstChoice]))
{
tailQueue->m_state = nextState;
return dequeue(tailQueue, firstChoice, result);
}
if (!isSetEmpty(tailQueue->m_queues[secondChoice]))
return dequeue(tailQueue, secondChoice, result); if (!isSetEmpty(tailQueue->m_queues[TAIL_DISMISSED]))
return dequeue(tailQueue, TAIL_DISMISSED, result); return 0;
}static int dequeue(TailQueue* tailQueue, int queueNumber, Tail* result)
{
int found = getTailFromSet(tailQueue->m_queues[queueNumber], 0, result);
if (found)
removeTailFromSet(tailQueue->m_queues[queueNumber], *result);
return found;
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |