aca-tasks/MonitorExample/producer.cpp

29 lines
1.0 KiB
C++
Raw Normal View History

#include "producer.h"
//---------------------------------------
template<typename T> QSemaphore Producer<T>::numProducts;
template<typename T> Monitor<T> * Producer<T>::mon;
template<> int (*Producer<int>::produce)(int) = NULL;
//---------------------------------------
template<typename T> void Producer<T>::initClass(int numP, Monitor<T> *m, T(*prod)(int)) {
mon = m;
numProducts.release(numP);
produce = prod;
}
//---------------------------------------
2023-12-02 14:29:28 +00:00
//Semaphore with Number of Resources -> create N Resources
//produce item -> get spot in queue -> put item into second queue
//activate consumers
template<typename T>
void Producer<T>::run() {
while (numProducts.tryAcquire()) { // While not all numProducts items are produced:
T item = (*produce)(ID); // Produce one item
T* aux = mon->canPut(); // Get place for item in emptySpotsQ
*aux = item; // Put item into emptySpotsQ
mon->donePutting(aux); // Give info to consumer threads
}
}
//---------------------------------------