C++ std::atomic<bool> solution with yielding
This solution uses no mutexes/locks, and it is somewhat faster than locking/conditionals on LeetCode\'s OJ. That being said, if you take this code and run it on
This solution uses no mutexes/locks, and it is somewhat faster than locking/conditionals on LeetCode\'s OJ. That being said, if you take this code and run it on your own machine, it may be a LOT slower than the one that uses locks/conditionals and has to wait/notify...So take this solution with a grain of salt, please...\n\n```\nclass FooBar\n{\nprivate:\n    int n;\n    std::atomic<bool> toPrintFoo;\n    \npublic:\n    FooBar(int n)\n    {\n        this->n = n;\n        this->toPrintFoo.store(true, std::memory_order_seq_cst);\n    }\n\n    void foo(function<void()> printFoo)\n    {\n        for (int i = 0; i < n;)\n        {\n            if (toPrintFoo.load(std::memory_order_seq_cst))\n            {\n                // printFoo() outputs "foo". Do not change or remove this line.\n        \t    printFoo();\n            \n                toPrintFoo.store(false, std::memory_order_seq_cst);\n                \n                i++;\n            }\n            else\n            {\n                // yield this thread (on a single core, letting the other thread take over)\n                // to the OS to determine whether higher or equal priority processes/threads\n                // can jump on the core...\n                std::this_thread::yield();\n            }\n        }\n    }\n\n    void bar(function<void()> printBar)\n    {\n        for (int i = 0; i < n;)\n        {\n            if (!toPrintFoo.load(std::memory_order_seq_cst))\n            {\n                // printFoo() outputs "foo". Do not change or remove this line.\n        \t    printBar();\n            \n                toPrintFoo.store(true, std::memory_order_seq_cst);\n                \n                i++;\n            }\n            else\n            {\n                // yield this thread (on a single core, letting the other thread take over)\n                // to the OS to determine whether higher or equal priority processes/threads\n                // can jump on the core...\n                std::this_thread::yield();\n            }\n        }\n    }\n};\n```
['C']