diff --git a/cpp-src/RaceWinnersThreadProblem.cc b/cpp-src/RaceWinnersThreadProblem.cc index a210199..e0223f8 100644 --- a/cpp-src/RaceWinnersThreadProblem.cc +++ b/cpp-src/RaceWinnersThreadProblem.cc @@ -38,10 +38,22 @@ #include #include #include +#include #undef SCHEDULER +//#define SCHEDULER using namespace std; +// condition variables to synchronize input and output threads +mutex inMutex; +condition_variable inCondVar; + +mutex outMutex; +condition_variable outCondVar; + +// pre-conditions for the above condition variables +// setup input thread to run initially +bool inputReady{false}, outputDone{true}; class Runner { public: @@ -58,9 +70,15 @@ class Runner { void input(list &runners) { #if !defined(SCHEDULER) + cout << "input: ns" << endl; while (true) { #endif - // Possible solution Code here + + // wait until ouput thread has finished processing the previous + // set of inputs + // note: this will always be true for the first time + unique_lock lck(outMutex); + outCondVar.wait(lck,[]{return outputDone;}); vector ranks(3); cout <<"Enter ranks for Dave, Jeff, Ben respectively"< &runners) { cout << "Invalid Input" << endl; } - // Possible solution Code here + //set the pre-conditions as appropriate and notify the + //output thread to begin processing + outputDone = false; + + { + lock_guard lck(inMutex); + inputReady = true; + } + inCondVar.notify_one(); + #if !defined(SCHEDULER) } #endif @@ -92,9 +119,14 @@ bool descending (pair &a, pair &b) { void output(list &runners) { #if !defined(SCHEDULER) + cout << "output: ns" << endl; while (true) { #endif - // Possible solution Code here + + // wait until input thread has finished processing + // i.e.: input is available for us to process + unique_lock lck(inMutex); + inCondVar.wait(lck,[]{return inputReady;}); vector< pair > winners; // data structure that holds count of Races where Runner Won for (auto &runner : runners) @@ -107,7 +139,16 @@ void output(list &runners) { } cout< lck(outMutex); + outputDone = true; + } + outCondVar.notify_one(); + #if !defined(SCHEDULER) } #endif