This commit is contained in:
Robin Dietzel 2023-12-02 14:55:13 +01:00
parent 71fad746b3
commit 04c37c5078

View File

@ -17,32 +17,35 @@
class Printer {
private:
QSemaphore &lockBC;
QSemaphore &lockC;
QSemaphore &lockBC_;
QSemaphore &lockC_;
QString name_;
public:
explicit Printer(QSemaphore &lockBC, QSemaphore &lockC) : lockBC(lockBC), lockC(lockC) {};
explicit Printer(QSemaphore &lockBC, QSemaphore &lockC, QString name) : lockBC_(lockBC), lockC_(lockC),
name_(name) {};
void printA() {
this->lockBC.release(1);
std::cout << "A\n";
this->lockBC_.release(1);
std::cout << name_.toStdString() << " A\n";
}
void printB() {
if (this->lockBC.tryAcquire(1, 10000)) {
if (this->lockC.available() == 0) {
this->lockC.release(1);
if (this->lockBC_.tryAcquire(1, 10000)) {
if (this->lockC_.available() == 0) {
this->lockC_.release(1);
}
std::cout << "B\n";
std::cout << name_.toStdString() << " B\n";
}
}
void printC() {
if (this->lockBC.tryAcquire(1, 10000)) {
if (this->lockC.tryAcquire(1, 10000)) {
std::cout << "C\n";
if (this->lockBC_.tryAcquire(1, 10000)) {
if (this->lockC_.tryAcquire(1, 10000)) {
std::cout << name_.toStdString() << " C\n";
} else {
this->lockBC.release(1);
this->lockBC_.release(1);
}
}
}
@ -50,18 +53,16 @@ public:
class Worker : public QThread {
private:
QSemaphore &lockBC;
QSemaphore &lockC;
Printer printer_;
public:
Worker(QSemaphore &lockBC, QSemaphore &lockC) : lockBC(lockBC), lockC(lockC) {};
Worker(QSemaphore &lockBC, QSemaphore &lockC, QString tname) : printer_(lockBC, lockC, tname) {};
protected:
void run() {
Printer print = Printer(this->lockBC, this->lockC);
print.printA();
print.printB();
print.printC();
printer_.printA();
printer_.printB();
printer_.printC();
}
};
@ -71,20 +72,12 @@ int main(int argc, char *argv[]) {
QSemaphore lockC(1);
QSemaphore lockBC(0);
Worker trd1(lockBC, lockC);
Worker trd2(lockBC, lockC);
Worker trd3(lockBC, lockC);
trd1.start();
trd2.start();
trd3.start();
// int N = 3;
// Worker *workers[N];
// for (int i = 0; i < N; i++) {
// workers[i] = new Worker(lockBC, lockC);
// workers[i]->run();
// }
int N = 3;
Worker *workers[N];
for (int i = 0; i < N; i++) {
workers[i] = new Worker(lockBC, lockC, QString("Thread %1").arg(i));
workers[i]->start();
}
return app.exec();
}