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