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

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

    #include 
    #include 
    #include 
    
    std::mutex mu;
    unsigned int change = 0;
    
    void printConsecutiveNumbers(int start, int end,unsigned int consecutive)
    {
        int x = start;
        while (x < end)
        {
            //each thread has check there time is coming or not
            if (change % consecutive == start)
            {
                std::unique_lock locker(mu);
                std::cout << "Thread " << start << " -> " << x << std::endl;
                x += consecutive;
                change++;
                //to counter overflow
                change %= consecutive;
            }
        }
    }
    
    int main()
    {
        //change num = 2 for printing odd and even
        const int num = 7;
        const int endValue = 1000;
        std::thread threads[num];
        //Create each consecutive threads
        for (int i = 0; i < num; i++)
        {
            threads[i] = std::thread(printConsecutiveNumbers, i, endValue, num);
        }
    
        //Joins all thread to the main thread
        for (int i = 0; i < num; i++)
        {
            threads[i].join();
        }
    
        return 0;
    }
    

提交回复
热议问题