Skip to content
Open
Changes from 3 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
38 changes: 31 additions & 7 deletions module4/exercises/03b_ping_pong_easier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
#include <chrono>
#include <condition_variable>
#include <atomic>
#include <sstream>
using namespace std;

class PingPong {
mutex m_;
condition_variable opponentsTurn_;
bool isPingTurn_ = true;
atomic_bool isPingTurn_{true};
int repetitions_;
atomic<bool> play_{true};

Expand All @@ -23,12 +24,20 @@ 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_.load(); });
cout << "Ping" << 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();
play_ = false;
opponentsTurn_.notify_all();
}
}

Expand All @@ -37,18 +46,33 @@ 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_.load(); });
cout << "Pong" << endl;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consecutive number is not printed

reps++;
isPingTurn_=true;
opponentsTurn_.notify_all();
}
if (reps >= repetitions_) {
// TODO: set play_ to false, display message, notify others to avoid deadlocks
std::stringstream notify;
notify << "Ping is finishing game. Num reps has reached " << reps << endl;
Comment thread
lukasz-plewa marked this conversation as resolved.
Outdated
cout << notify.str();
play_ = false;
opponentsTurn_.notify_all();
}
}

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