C++ | Modern approach with Condition Variable and Lambda Functions
\n#include <condition_variable>\n#include <mutex>\n\nclass ZeroEvenOdd {\npublic:\n  ZeroEvenOdd(int n) : i_{0}, n_{n}, state_{State::Odd}, zero_{true} {}\n\n  
```\n#include <condition_variable>\n#include <mutex>\n\nclass ZeroEvenOdd {\npublic:\n  ZeroEvenOdd(int n) : i_{0}, n_{n}, state_{State::Odd}, zero_{true} {}\n\n  void zero(function<void(int)> printNumber) {\n    auto transitionFunction = [&]() { \n      printNumber(0); \n      ++i_;\n      zero_ = false;\n    };\n    auto predicateFunction = [&]() -> bool { \n      return zero_; \n    };\n    \n    worker(transitionFunction, predicateFunction);\n  }\n\n  void even(function<void(int)> printNumber) {\n    auto transitionFunction = [&]() {\n      printNumber(i_);\n      state_ = State::Odd;\n      zero_ = true;\n    };\n    auto predicateFunction = [&]() -> bool {\n      return !zero_ && state_ == State::Even;\n    };\n    \n    worker(transitionFunction, predicateFunction);\n  }\n\n  void odd(function<void(int)> printNumber) {\n    auto transitionFunction = [&]() {\n      printNumber(i_);\n      state_ = State::Even;\n      zero_ = true;\n    };\n    auto predicateFunction = [&]() -> bool {\n      return !zero_ && state_ == State::Odd;\n    };\n    \n    worker(transitionFunction, predicateFunction);\n  }\nprivate:\n  enum class State {\n    Odd,\n    Even\n  };\n  \n  int i_;\n  int n_;\n  \n  std::condition_variable cond_;\n  std::mutex mutex_;\n  \n  State state_;\n  bool zero_;\n  \n  inline bool outOfBounds() {\n    // We have to check if zero_ is true because we only increment when zero is true\n    // This prevents an off-by-one logic error. \n    return i_ == n_ && zero_ == true; \n  }\n  \n  void worker(function<void()> transitionFunction, function<bool()> predicateFunction) {\n    while (!outOfBounds()) {\n      {\n        std::unique_lock<std::mutex> guard{mutex_};\n        cond_.wait(guard, [&]() -> bool {\n          return outOfBounds() || predicateFunction();\n        });\n        \n        if (outOfBounds())\n          break;\n       \n        transitionFunction();\n      }\n      cond_.notify_all();\n    }\n  }\n};\n```
['C']