Given the code below Complete the following Experience the race conditions and c
ID: 3600520 • Letter: G
Question
Given the code below
Complete the following
Experience the race conditions and context switching race.c … for playing with ECE437 #include #include #include include struct(int balance[2]:) Bank=K100. 100)); //global variable defined void* MakeTransactionsIlroutine for thread execution int i, j, tmp1, tmp2, rint; double dummy; for (i=0; i =0&& ((tmp2-Bank. balance[1])-rintpz0) { Bank.balanceol = tmp1+ nnt; for (j=0;rint" 100, j++) {dummy-2.345*8.765/1 .234:) // spend time on purpose Bank.balance[1] = tmp2-rint; return NULL int main(int argc, char "argv) int i, void* voidptr-NULL; pthread t tid 2] srand(getpid0) printf("Init balances A:%d + B:%d ==> %d/n", for (i=0; iExplanation / Answer
In this modified code mutex is used to overcome race condition. See the mutex usage. Now you will get expected result.
/******************************/
/*
* mutex.c
*
* Created on: 25-Oct-2017
* Author:
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t muid;
struct {
int balance[2];
}Bank={{100,100}}; //global variable defined
void* MakeTransactions(){ //routine for thread execution
int i,j,tmp1,tmp2,rint;
double dummy;
pthread_mutex_lock(&muid); //Lock the mutex, only one thread will execute the below code
for( i=0;i<100;i++)
{
rint=(rand()%30)-15;
if(((tmp1=Bank.balance[0])+rint)>=0 && ((tmp2=Bank.balance[1])-rint)>=0){
Bank.balance[0]=tmp1+rint;
for(j=0;j<rint*100;j++)
dummy=2.345*8.765/1.234;
Bank.balance[1]=tmp2-rint;
}
}
pthread_mutex_unlock(&muid); //unlock mutex when execution finish
return NULL;
}
int main()
{
int i;
void* voidptr=NULL;
pthread_t tid[2];
pthread_mutex_init(&muid,NULL); // Init the mutex here to get the mutex id
srand(getpid());
printf("Init balances A: %d + B:%d==> %d! ",
Bank.balance[0],Bank.balance[1],Bank.balance[0]+Bank.balance[1]);
for(i=0;i<2;i++)
if(pthread_create(&tid[i],NULL,MakeTransactions,NULL)){
perror("Error in thread creating ");
return 1;
}
for(i=0;i<2;i++)
if(pthread_join(tid[i],(void*)&voidptr)){
perror("Error in thread joining ");
return 1;
}
printf("Lets check the balances A: %d+B:%d==>%d?=200",
Bank.balance[0],Bank.balance[1],Bank.balance[0]+Bank.balance[1]);
return 0;
}
Here is the result before mutex usage
/*****************************/
Init balances A: 100 + B:100==> 200!
Lets check the balances A: 220+B:15==>235?=200
Here is the result after mutex usage
/*****************************/
Init balances A: 100 + B:100==> 200!
Lets check the balances A: 13+B:187==>200?=200
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.