Print even and odd using two thread in synchronized way

 Print even and odd using two thread in synchronized way :

Example :  ODD Thread will print  1

                   EVEN Thread will print  2

                 ----------------------------------------------

                 ODD Thread will print till pre-define range

                 EVEN Thread will print till pre-define range


Solutions :


#include <iostream>

#include <thread>

#include <mutex>

#include <condition_variable>

#define MAXSIZE 1000

using namespace std;

mutex mu;

condition_variable con;

int mycount = 1;


void printodd() {

       cout << "i am in ODD thread" << endl;

                while (mycount < MAXSIZE) {

        unique_lock<mutex> mylock(mu);

con.wait(mylock, []() { return (mycount % 2 != 0); });

cout << " ODD Thread " << mycount << endl;

mycount++ ;

mylock.unlock();

con.notify_all();

}

}


void printeven() {


cout << "i am in EVEN thread" << endl;

        while (mycount < MAXSIZE) {

        unique_lock<mutex> mylock(mu);

con.wait(mylock, []() { return (mycount % 2 == 0); });

        cout << " EVEN Thread " << mycount << endl;

mycount++ ;

        mylock.unlock();

        con.notify_all();

        }

}

int main() {

        cout << "i am in Main...." << endl;

        thread eventh(printeven);

thread oddth(printodd);

        eventh.join();

oddth.join();

return 0;

}


Comments

Popular posts from this blog

Dynamic Memory allocation in C++ for 1d, 2d and 3d array

Write Your Own String Class:

Printing the odd and even no using Pthread