C++ solution using mutex + CV (w/ explanation)
This is basically a semaphore. We use the flag fooTurn in the predicate of wait() to determine if the lock should be freed.\n\nBecause there are only two states
This is basically a semaphore. We use the flag `fooTurn` in the predicate of `wait()` to determine if the lock should be freed.\n\nBecause there are only two states (foo and bar), we can get away with using a boolean for the flag and `notify_one()`. If there were more states, we could scale this using an int flag and `notify_all()`.\n\nIf you\'re wondering why `foo` runs for the first time at all despite the `cv.wait()`, it\'s because the line is actually a shorthand for `while (!fooTurn) { cv.wait(lock); }`. Since `fooTurn` is initialized as true, the `cv.wait()` gets ignored.\n\n```\nclass FooBar {\nprivate:\n    int n;\n    std::mutex mtx;\n    std::condition_variable cv;\n    bool fooTurn = true;  // is it foo\'s turn to run?\n\npublic:\n    FooBar(int n) {\n        this->n = n;\n    }\n\n    void foo(function<void()> printFoo) {\n        for (int i = 0; i < n; i++) {\n            std::unique_lock<std::mutex> lock(mtx);\n            cv.wait(lock, [this] { return fooTurn; });\n\t\t\t\n        \tprintFoo();\n\t\t\t\n            fooTurn = false;\n            cv.notify_one();\n        }\n    }\n\n    void bar(function<void()> printBar) {\n        for (int i = 0; i < n; i++) {\n            std::unique_lock<std::mutex> lock(mtx);\n            cv.wait(lock, [this] { return !fooTurn; });\n\t\t\t\n        \tprintBar();\n\t\t\t\n            fooTurn = true;\n            cv.notify_one();\n        }\n    }\n};\n```
['C']