aca-tasks/task4/include/producer.h

38 lines
1.1 KiB
C
Raw Permalink Normal View History

2023-12-02 15:04:12 +00:00
#pragma once
#include "monitor.h"
#include <QThread>
#include <QSemaphore>
template<typename T>
class Producer : public QThread {
private:
static QSemaphore numProducts;
int ID;
static Monitor<T> *mon;
public:
static T (*produce)(int);
static void initClass(int numP, Monitor<T> *m, T(*prod)(int)) {
mon = m;
numProducts.release(numP);
produce = prod;
};
Producer(int i) : ID(i) {};
Producer(QObject *parent, int id);
void 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
}
};
};
template<typename T> QSemaphore Producer<T>::numProducts;
template<typename T> Monitor<T> * Producer<T>::mon;
template<> int (*Producer<int>::produce)(int) = NULL;