Simple Producer/Consumer Example
Assume we have a simple queue class:
template<class T> class Queue {
public:
void enqueue(const T & item);
T dequeue();
};
- Producer threads read items from somewhere and place them on the queue by calling enqueue.
- Consumer threads fetch items from the queue by calling dequeue.
- The queue is a critical region and the consumer threads must be suspended when the queue is empty.
#include <list >
template<class T> class Queue {
public:
void enqueue(const T & item) {
m_q.push_back(item);
}
T dequeue() {
T item = m_q.front();
m_q.pop_front();
return item;
}
private:
list<T> m_q;
};
#include <list >
#include <JTC/JTC.h >
template<class T> class Queue : JTCMonitor {
public:
void enqueue(const T & item) {
JTCSynchronized lock(*this);
m_q.push_back(item);
notify();
}
T dequeue() {
JTCSynchronized lock(*this);
while (m_q.size() == 0) {
try {
wait();
} catch (const JTCInterruptedException & ) {
}
}
T item = m_q.front();
m_q.pop_front();
return item;
}
private:
list<T> m_q;
};
Corba Consumer
Corba Fundamentals