aca-tasks/MonitorExample/monitor.cpp

70 lines
2.6 KiB
C++
Raw Normal View History

#include "monitor.h"
template<typename T>
Monitor<T>::Monitor(int n) {
buffer = new T[n];
for(int i=0;i<n;i++)
emptySpotsQ.push(&buffer[i]); // Initialize emptySpotsQ with buffer places
}
//-----------------------------------------
template<typename T>
Monitor<T>::~Monitor() {
delete []buffer;
}
//-----------------------------------------
//producer tries to put an item:
// lock l
// wait for spot in putting queue
// get first spot in putting queue
template<typename T>
T* Monitor<T>::canPut() {
QMutexLocker ml(&l); // Lock entry controlling mutex l
while (emptySpotsQ.size() == 0) // If no free place in emptySpots queue:
full.wait(&l); // Block until condition variable full is given free by mutex l
T *aux = emptySpotsQ.front(); // Get place in emptySpotsQ
emptySpotsQ.pop(); // ?? Free one place in emptySpotsQ ?? (documentation of class queue currently not available)
return aux; // Return pointer to place in emptySpotsQ for item to be produced
}
//-----------------------------------------
//consumer tries to take an item:
// lock l
2023-12-02 14:29:28 +00:00
// wait until items are in itemq
// take item
template<typename T>
T* Monitor<T>::canGet() {
QMutexLocker ml(&l); // Lock entry controlling mutex l
while (itemQ.size() == 0) // If no item in itemQ:
empty.wait(&l); // Block until condition variable empty is given free by mutex l
T* temp = itemQ.front(); // Get item out of itemQ
itemQ.pop(); // ?? Free one place in itemQ ?? (documentation of class queue currently not available)
return temp; // Return pointer to item in itemQ, which will be consumed
}
//-----------------------------------------
//producer is done with producing and wants to put that item:
// lock l
// push produced item to itemQ
// wake waiting consumer
template<typename T>
void Monitor<T>::donePutting(T *x) {
QMutexLocker ml(&l); // Lock entry controlling mutex l
itemQ.push(x); // Push place with produced item into itemQ
empty.wakeOne(); // Notify one consumer thread waiting for condition variable empty
}
//-----------------------------------------
2023-12-02 14:29:28 +00:00
//consumer is done with taking an item:
// lock l
// enlarge producer queue by one
// notify a producer of new spot
template<typename T>
void Monitor<T>::doneGetting(T *x) {
QMutexLocker ml(&l); // Lock entry controlling mutex l
emptySpotsQ.push(x); // Give free the buffer place which had hold the consumed item by pushing in into emptySpotsQ
full.wakeOne(); // Notify one producer thread waiting for condition variable empty
}
//************************************************************