Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module4 homework ping pong #53

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions module4/exercises/03b_ping_pong_easier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <chrono>
#include <condition_variable>
#include <atomic>
#include <sstream>
using namespace std;

class PingPong {
Expand All @@ -23,12 +24,17 @@ class PingPong {
while (reps < repetitions_ and play_)
{
unique_lock<mutex> l(m_);
// TODO: wait to be used here + printing, reps incrementation, chainging turn to pong
this_thread::sleep_for(500ms);
opponentsTurn_.wait(l, [&] {return isPingTurn_; });
cout << "Ping " << reps << endl;
reps++;
isPingTurn_ = false;
opponentsTurn_.notify_all();
}
if (reps >= repetitions_)
{
// TOOD: only print message here
std::stringstream notify;
notify << "Ping is finishing game. Num reps has reached " << reps << endl;
cout << notify.str();
}
}

Expand All @@ -37,18 +43,34 @@ class PingPong {
while (reps < repetitions_ and play_)
{
unique_lock<mutex> l(m_);
// TODO: wait to be used here + printing, reps incrementation, chainging turn to ping
this_thread::sleep_for(500ms);
opponentsTurn_.wait(l, [&] {return !isPingTurn_; });
cout << "Pong " << reps << endl;
reps++;
isPingTurn_ = true;
if (reps >= repetitions_) {
play_ = false;
}
opponentsTurn_.notify_all();
}
if (reps >= repetitions_) {
// TODO: set play_ to false, display message, notify others to avoid deadlocks
std::stringstream notify;
notify << "Pong is finishing game. Num reps has reached " << reps << endl;
cout << notify.str();
}
}

void stop([[maybe_unused]] chrono::seconds timeout) {
unique_lock<mutex> l(m_);
// TODO: wait_for to be used here. Check for a return value and set play_ to false

auto ret = opponentsTurn_.wait_for(l, timeout, [&] {return not play_.load(); });
if (ret) {
cout << "Game finished.\n";
}
else {
cout << "Stop is finishing game - timeout.\n";
play_ = false;
opponentsTurn_.notify_one();
}
}
};

Expand Down