aca-tasks/task4/include/consumer.h

36 lines
1012 B
C
Raw Normal View History

2023-12-02 15:04:12 +00:00
#pragma once
#include "monitor.h"
#include <QThread>
#include <QSemaphore>
template<typename T>
class Consumer : public QThread {
private:
int ID;
static Monitor<T> *mon;
static QSemaphore numProducts;
public:
static void (*consume)(T i, int);
static void initClass(int numP, Monitor<T> *m, void (*cons)(T, int)) {
numProducts.release(numP);
mon = m;
consume = cons;
};
Consumer(int i) : ID(i) {};
void run() {
while (numProducts.tryAcquire()) { // While not all numProducts are consumed:
T* aux = mon->canGet(); // Get pointer to item in itemQ
T item = *aux; // Take the item out of itemQ
mon->doneGetting(aux); // Give info to producer threads
(*consume)(item,ID); // Consume one item
}
};
};
template<typename T> QSemaphore Consumer<T>::numProducts;
template<typename T> Monitor<T> *Consumer<T>::mon;
template<> void (*Consumer<int>::consume)(int, int) = NULL;