Create a pair of programs following the producer / consumer model to pass messag
ID: 3736591 • Letter: C
Question
Create a pair of programs following the producer / consumer model to pass messages between each other using a message queue. The consumer program will be responsible for:
* setting up the queue with the following key: ftok(".", 'Z')
* displaying characters that are sent by the producer where the message type is 100
* removing the queue and exiting once a lowercase q or uppercase Q is received
The producer will:
* access the queue created by the consumer
* prompt the user to input one keyboard character at a time followed by the enter key
* send the keyboard character to the consumer process via message queue
Also implement error handling in the producer and consumer programs to account for the possibility of the queue creation failing for reasons specified in the man pages of the msgget function
Explanation / Answer
public class ProducerConsumer { Queue _MyQueue; private Object _lockObject; public ProducerConsumer(Queue MyQueue, Object lockObject) { this._MyQueue = MyQueue; _lockObject = lockObject; } public void produce() { int msgId =0; lock (_lockObject) { while (msgId < 10) { Thread.Sleep(500); Monitor.Wait(_lockObject); msgId++; message msg = new message { Id = msgId, body = "Message " + msgId, sendDate = DateTime.Now }; Console.WriteLine("Sending message : {0}", msg.body); _MyQueue.Enqueue(msg); Monitor.Pulse(_lockObject); } } } public void consume() { lock (_lockObject) { Monitor.Pulse(_lockObject); while (Monitor.Wait(_lockObject, 1000)) { if (_MyQueue.Count == 0) { continue; } message msg = _MyQueue.Dequeue(); Console.WriteLine (" Message : {0} received at : {1}", msg.body, msg.sendDate); Monitor.Pulse(_lockObject); } } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.