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

前端 未结 10 1165
后悔当初
后悔当初 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:02

    Using condition_variable

    #include 
    #include 
    #include 
    #include 
    
    std::mutex mu;
    std::condition_variable cond;
    int count = 1;
    
    void PrintOdd()
    {
        for(; count < 100;)
        {
            std::unique_lock locker(mu);
            cond.wait(locker,[](){ return (count%2 == 1); });
            std::cout << "From Odd:    " << count << std::endl;
            count++;
            locker.unlock();
            cond.notify_all();
        }
    
    }
    
    void PrintEven()
    {
        for(; count < 100;)
        {
            std::unique_lock locker(mu);
            cond.wait(locker,[](){ return (count%2 == 0); });
            std::cout << "From Even: " << count << std::endl;
            count++;
            locker.unlock();
            cond.notify_all();
        }
    }
    
    int main()
    {
        std::thread t1(PrintOdd);
        std::thread t2(PrintEven);
        t1.join();
        t2.join();
        return 0;
    }
    

提交回复
热议问题