aca-tasks/MonitorExample/main.cpp

72 lines
1.8 KiB
C++
Raw Normal View History

/*
============================================================================
Author : G. Barlas
Version : 1.0, September 2015
: 1.1, 16.12.2019 - Comments added (H. Weber)
: 1.2, 27.01.2022 - Console output improved (H. Weber, S. Stahl)
License : V 1.0 released under the GNU GPL 3.0
Description : Producer/consumer example using a monitor.
To compile : qmake monitor2ProdCons.pro; make
============================================================================
*/
#include "monitor.h"
#include "producer.h"
#include "consumer.h"
#include <iostream>
#include <unistd.h>
using namespace std;
int produce(int id) {
QMutex prodBinSem;
static int i = 0;
prodBinSem.lock();
int j = i++;
prodBinSem.unlock();
printf("%3d produced by producer %d\n", j, id); // i to j
return j;
}
void consume(int i, int ID) {
printf("%3d consumed by consumer %d\n", i, ID);
}
int main(int argc, char *argv[]) {
Monitor<int> m;
int N = 4; // Count of Producer objects (each is one QThread)
int M = 3; // Count of Consumer objects (each is one QThread)
int numP = 10; // Count of produced/consumed items for all Producer/Consumer threads combined
printf("%d items produced by %d producers and consumed by %d consumers\n", numP, N, M);
Producer<int>::initClass(numP, &m, &produce);
Consumer<int>::initClass(numP, &m, &consume);
Producer<int> *p[N];
Consumer<int> *c[M];
//Producers start producing
for (int i = 0; i < N; i++) {
p[i] = new Producer<int>(i);
p[i]->start();
}
//Consumer start consuming
for (int i = 0; i < M; i++) {
c[i] = new Consumer<int>(i);
c[i]->start();
}
for (int i = 0; i < N; i++)
p[i]->wait();
for (int i = 0; i < M; i++)
c[i]->wait();
return 0;
}