Posts

Showing posts from March, 2024

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" << en