printing odd and even number printing alternately using threads in C++

前端 未结 10 1093
后悔当初
后悔当初 2021-01-03 02:09

Odd even number printing using thread I came across this question and wanted to discuss solution in C++ . What I can think of using 2 binary semaphores odd and even semapho

10条回答
  •  生来不讨喜
    2021-01-03 03:04

    Solution using condition variable.

    #include
    #include
    #include
    using namespace std;
    mutex oddevenMu;
    condition_variable condVar;
    int number = 1;
    
    void printEvenOdd(bool isEven, int maxnubmer)
    {
        unique_lock ul(oddevenMu);
        while (number < maxnubmer)
        {
            condVar.wait(ul, [&]() {return number % 2 == isEven;});
            cout << number++ << " ";
            condVar.notify_all();
        }
    
    }
    
    int main(string args[])
    {
        thread oddThread(printEvenOdd, false, 100);
        thread evenThread(printEvenOdd, true, 100);
        oddThread.join();
        evenThread.join();
        return 0;
    }
    

提交回复
热议问题