C++ implements two threads to alternately print odd and even numbers

Hits: 0

#include<iostream>
#include<mutex>
#include<thread>
#include<condition_variable>
#include<Windows.h>
using namespace std;

mutex mut;
condition_variable cond1, cond2;
int g_nums = 1;


//Thread 1 
void  thread1 ()
 {
     while ( 1 )
    {
        unique_lock<mutex> locker(mut);
        cout << "Thread1:" << g_nums << endl;
        g_nums++;
        cond2.notify_one();
        cond1.wait(locker);
        locker.unlock();
        Sleep(1000);
    }
}

//Thread 2 
void  thread2 ()
 {
     while ( 1 )
    {
        Sleep(1000);
        unique_lock<mutex> locker(mut);
        cout << "Thread2:" << g_nums << endl;
        g_nums++;
        cond1.notify_one();
        cond2.wait(locker);
        locker.unlock();
    }
}
int main()
{
    thread t1(thread1);
    thread t2(thread2);
    t1.join();
    t2.join();
    system("pause");
    return 0;
}

You may also like...

Leave a Reply

Your email address will not be published.