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

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

    Solution is based on C++11 critical code section aka mutex.

    Here's the working code, followed by an explanation.

    Tested and working on VS2013:

    using namespace std;
    #include 
    #include 
    #include 
    #include 
    
    std::mutex mtx;
    
    void oddAndEven(int n, int end);
    
    int main()
    {
    std::thread odd(oddAndEven, 1, 10);
    std::thread Even(oddAndEven, 2, 10);
    
    odd.join();
    Even.join();
    
    return 0;
    }
    
    
    
    void oddAndEven(int n, int end){
    int x = n;
    for (; x < end;){
        mtx.lock();
        std::cout << n << " - " << x << endl;
        x += 2;
        mtx.unlock();
        std::this_thread::yield();
        continue;
     }
    }
    

    i.e:

    Thread odd goes to method oddAndEven with starting number 1 thus he is the odd. He is the first to acquire the lock which is the mtx.lock().

    Meanwhile, thread Even tries to acquire the lock too but thread odd acquired it first so thread Even waits.

    Back to thread odd (which has the lock), he prints the number 1 and releases the lock with mtx.unlock(). At this moment, we want thread Even to acquire lock and to print 2 so we notify thread Even by writing std::this_thread::yield(). Then thread Even does the same.

    etc etc etc.

提交回复
热议问题