#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex m1,m2;
int x=0,y=0;

void consume_xy()
{
    while(1)
        {
            int xplusy =0;
            int count = 5;
              int lockresult = std::try_lock(m1,m2);
              if(lockresult == -1)
              {
                  while(x!=0 && y!=0)
                      {
                          --count;
                          xplusy+=x+y;
                          x=0;
                          y=0;
                          cout<<"xplusy : "<<xplusy<<endl; 
                      }
                  m1.unlock();
                  m2.unlock();
                  if(count ==0) break;
              }
        }
    
}

void increment_xy(int& xory, mutex& m,char c)
{
       for(int i=0;i<5;i++)
        {
             m.lock();
                 xory++;
            cout<< c<<" "<<xory<<endl;
             m.unlock();
             std::this_thread::sleep_for(std::chrono::seconds(1));
        }
}




int main() {
    
     thread t1(increment_xy, std::ref(x), std::ref(m1),'X');
     thread t2(increment_xy, std::ref(y), std::ref(m2),'Y');
     thread t3(consume_xy);

     t1.join();
     t2.join();
     t3.join();
    
    
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: