Professional Documents
Culture Documents
Output :
2. Write a Program to avoid Race condition using Mutex Locks.
Create two threads: one to increment the value of a shared variable and second to decrement
the value of shared variable. Both the threads make use of locks so that only one of the
threads is executing in its critical section.
#include<bits/stdc++.h>
using namespace std;
int shared = 1;
mutex m;
void fun1()
{
int x;
cout << "Thread1 trying to acquire lock " << endl;
m.lock();
cout << "Thread1 acquired lock " << endl;
x = shared;
cout << "Thread1 reads the value of shared variable as " << x << endl;
x++;
cout << "Local updation by Thread1: " << x << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
shared = x;
cout << "Value of shared variable updated by Thread1 is: " << shared <<
endl;
m.unlock();
cout << "Thread1 released the lock " << endl;
}
void fun2()
{
int y;
cout << "Thread2 trying to acquire lock " << endl;
m.lock();
cout << "Thread2 acquired lock " << endl;
y = shared;
cout << "Thread2 reads the value of shared variable as " << y << endl;
y--;
cout << "Local updation by Thread2: " << y << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
shared = y;
cout << "Value of shared variable updated by Thread2 is: " << shared <<
endl;
m.unlock();
cout << "Thread2 released the lock " << endl;
}
int main()
{
thread t1(fun1);
thread t2(fun2);
t1.join();
t2.join();
cout << "Final value of shared is " << shared << endl;
return 0;
}
Output :
3. Write a Program to avoid Race condition using Semaphore.
Create two threads: one to increment the value of a shared variable and second to decrement
the value of shared variable. Both the threads make use of semaphore so that only one of the
threads is executing in its critical section.
Output :