C++ Semaphore solution
c++\n#include <semaphore.h> // from POSIX\n\nclass FooBar \n{\npublic:\n  FooBar(int n) \n  {\n    this->n = n;\n    sem_init(&foo_, 0, 1);\n    sem_init(&bar_,
```c++\n#include <semaphore.h> // from POSIX\n\nclass FooBar \n{\npublic:\n  FooBar(int n) \n  {\n    this->n = n;\n    sem_init(&foo_, 0, 1);\n    sem_init(&bar_, 0, 0);\n  }\n  \n  ~FooBar()\n  {\n    sem_destroy(&foo_); \n    sem_destroy(&bar_); \n  }\n\n  void foo(function<void()> printFoo) \n  {\n    for (int i = 0; i < n; i++) \n    {\n      sem_wait(&foo_);\n      // printFoo() outputs "foo". Do not change or remove this line.\n      printFoo();\n      sem_post(&bar_);\n      std::this_thread::yield();\n    }\n  }\n\n  void bar(function<void()> printBar) \n  {\n    for (int i = 0; i < n; i++) \n    {\n      sem_wait(&bar_);\n      // printBar() outputs "bar". Do not change or remove this line.\n      printBar();\n      sem_post(&foo_);\n      std::this_thread::yield(); \n    }\n  }\n  \nprivate:\n  int n;\n  sem_t foo_;\n  sem_t bar_; \n};\n```\n\n<br />\n\n*edit:*\nSemaphores, along with other threading primitives, are a confirmed C++2a library feature ([feature list on cppreference](https://en.cppreference.com/w/cpp/compiler_support), [thread support library on cppreference](https://en.cppreference.com/w/cpp/thread), and [latest published proposal on synchronization primitives](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1135r6.html)). For reference, leetcode compiles with "g++ 8.2 using the latest C++ 17 standard" at the time of writing. With this in mind, I wanted to modify the previous solution to be more C++ idiomatic and applicable to future versions of C++.\n\n```c++\n#include <semaphore.h> // from POSIX\n\n// RAII class for POSIX semaphore.\nclass counting_semaphore\n{\npublic:\n  counting_semaphore(unsigned int start)\n  {\n    sem_init(&sem_, 0, start);\n  }\n  \n  ~counting_semaphore()\n  {\n    sem_destroy(&sem_);\n  }\n  \n  void acquire()\n  {\n    sem_wait(&sem_);\n  }\n  \n  void release()\n  {\n    sem_post(&sem_);\n  }\n  \nprivate:\n  sem_t sem_;\n};\n\nclass FooBar \n{\npublic:\n  FooBar(int n) \n  {\n    this->n = n;\n  }\n  \n  void foo(function<void()> printFoo) \n  {\n    for (int i = 0; i < n; i++) \n    {\n      foo_.acquire();\n      // printFoo() outputs "foo". Do not change or remove this line.\n      printFoo();\n      bar_.release();\n      std::this_thread::yield();\n    }\n  }\n\n  void bar(function<void()> printBar) \n  {\n    for (int i = 0; i < n; i++) \n    {\n      bar_.acquire();\n      // printBar() outputs "bar". Do not change or remove this line.\n      printBar();\n      foo_.release();\n      std::this_thread::yield(); \n    }\n  }\n  \nprivate:\n  int n;\n  counting_semaphore foo_{1};\n  counting_semaphore bar_{0}; \n};\n```
['C']