I'm right now working on a school projection and i have some problems with sync'ing 3 threads (2 threads + mian thread). The description says that i have to print 100x "ping" then 100x"pong" and 100x"\n", BUT in this order :
PingPong\n and so on...
when i start my code like I have it right now it just prints 100xPing then 100xPong and then 100x\n out, and I cant understand why :(
The Point which i cant understnad is , the while should stop when i set counter to 1 and it should open cond.wait(); after that it shoudl move to pong() and so on...
Here is the code:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <atomic>
using namespace std;
mutex m; // Mutex
// Bedingungsvariable
condition_variable cond;
atomic<int> counter = 0;
bool done= true;
void ping() {
unique_lock <mutex > lock{ m }; // m sperren
while (counter != 0) {
cond.wait(lock); //sperren und dann wieder freigeben
}
while (counter == 0) {
for (int i = 0; i < 100; i++) {
cout << "Ping";
counter = 1;
cond.notify_one();
}
}
}
void pong() {
unique_lock <mutex > lock{ m }; // m sperren
while (counter != 1) {
cond.wait(lock);
}
while (counter == 1) {
for (int i = 0; i < 100; i++) {
cout << "Pong";
counter = 2;
cond.notify_one();
}
}
}
int main() {
thread t1(pong);
thread t(ping); // Zweiten Thread starten
unique_lock <mutex > lock{ m }; // m sperren
while (counter != 2) cond.wait(lock);
while (counter == 2) {
for (int i = 0; i < 100; i++) {
cout << "\n";
counter = 0;
cond.notify_one();
}
}
lock.unlock(); // Mutex freigeben
t.join();
t1.join();
system("PAUSE");
return EXIT_SUCCESS;
}