Message queues in an operating system There are times that programs need to communicate with each other. Unix operating system provides message queue as one of the mechanisms to facilitate communication. Program #1 Program #2 front rear Send a message to the queue Take a message from the queue
A Simple Array-Based Implementation To implement a queue with an array, we need: 1.An array of the size N 2.An index f for the front element 3.An index r for next empty slot or cell Q: … 012 r N - 1 f
As objects are enqueued and dequeued, the queue moves along in the array. For example: fr After enqueue: f r After dequeue: f r
When we increment f or r, we compute the result as (f + 1) mod N or (r + 1) mod N. In Java, the modulo operator is % (remainder operator). For example, if r = N - 1, then (r + 1) = N, therefore, (r + 1) mod N = 0 The value of r wraps around from N to 0. Q: … 0 12 rf N - 1
Initially, we assign r = f = 0, indicating that the queue is empty. During the process, we may meet a situation where r = f = i (0 < i < N), which also indicates the queue is empty. Now we assume that we enqueue N objects into Q without dequeueing any of them: Q: … 012 r f N - 1 Then, we have r = f = 0. But in this case, we have a full queue. In general, when r = f = i (0 < i < N), it is possible that we have a full queue.
Problem: r = f may indicate that the queue is empty or that the queue is full. Solution: when |r – f| = N – 1, report that the queue is full.
Algorithms: size(): return the number (N - f + r) mod N 012N-1N+r-1 If r f, then r - f 0 N + (r - f ) N (N - f + r) mod N = - f + r = r - f If r 0 N - f + r = N – (f - r ) < N (N - f + r) mod N = N - f + r
Algorithms: isEmpty( ): return the result of the evaluation of the relationship f = r f r
Algorithms: front( ): if the queue is empty throw a QueueEmptyException else return element Q[f] Q: … 012 r N - 1 f
enqueue(o): if queue size is N - 1 throw a QueueFullException else store the object to Q[r] assign (r + 1) mod N to r Q: … 012 r N - 1 f (r + 1) mod N
dequeue( ): if queue size is empty throw a QueueEmptyException else save the element Q[f] to a variable temp make the element Q[f] a null object assign (f + 1) mod N to f Q: … 012 r N - 1 f (f + 1) mod N