In: Computer Science
example_thread.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int shared= 0;
void race(void);
int main(){
pthread_t player1, player2, player3;
pthread_create(&player1, NULL, (void *)race,
NULL);
pthread_create(&player2, NULL, (void *)race,
NULL);
pthread_create(&player3, NULL, (void *)race,
NULL);
pthread_join(player1, NULL);
pthread_join(player2, NULL);
pthread_join(player3, NULL);
printf("Total Number = %d\n", shared);
return 0;
}
void race(void) {
long i,tmp;
for(i=1; i<=200000; i++) {
tmp = shared;
tmp = tmp + 1;
shared = tmp;
}
}
1. Use both Mutex lock and Semaphore to address the racing problem in the following program (example_thread.c). Please make sure that your output is always equal to 600000.
2. Use your Semaphore program to generate an example with deadlock problem.
1)MUTEX LOCK AND SEMAPHORE TO ADDRESS THE RACING PROBLEM
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int shared= 0;
void race(void);
int main(){
pthread_t player1, player2, player3;
pthread_create(&player1, NULL, (void *)race,
NULL);
pthread_create(&player2, NULL, (void *)race,
NULL);
pthread_create(&player3, NULL, (void *)race,
NULL);
pthread_join(player1, NULL);
pthread_join(player2, NULL);
pthread_join(player3, NULL);
printf("Total Number = %d\n", shared);
return 0;
}
void race(void) {
long i,tmp;
for(i=1; i<=600000; i++) {
tmp = shared;
tmp = tmp + 1;
shared = tmp;
}
}
2)SEMAPHORE PROGRAM TO GENERATE AN EXAMPLE WITH DEADLOCK PROGRAM
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "sections.h"
#include "mdat.h"
// TODO: Declare shared variables here
int numPhils;
sem_t * sem_arr;
void sectionInitGlobals(int numPhilosophers)
{
// TODO: Complete this function
int i;
char char_arr[50];
sem_t arr[numPhilosophers];
numPhils = numPhilosophers;
for(i = 0; i < numPhilosophers; i++)
{
sprintf(char_arr,"%d", i);
mdat_sem_init(char_arr, &arr[i], 0, 0);
}
sem_arr = arr;
}
void sectionRunPhilosopher(int philosopherID, int
numRounds)
{
int lChopstick = philosopherID;
int rChopstick;
int left;
int right;
int i;
int hasEaten;
int hasLeft;
int hasRight;
if(philosopherID == 0)
rChopstick = numPhils - 1;
else
rChopstick = philosopherID - 1;
for(i = 0; i < numRounds; i++)
{
hasEaten = 0;
hasLeft = 0;
hasRight = 0;
while(hasEaten == 0)
{
sem_getvalue(&sem_arr[lChopstick], &left);
if(left >= 0 || hasLeft == 1)
{
hasLeft = 1;
}
else
{
mdat_sem_wait(&sem_arr[lChopstick]);
}
sem_getvalue(&sem_arr[rChopstick], &right);
if(right >= 0 && hasLeft != 0)
{
hasRight = 1;
}
else
{
mdat_sem_wait(&sem_arr[rChopstick]);
}
if(hasLeft != 0 && hasRight != 0)
{
eat();
hasEaten = 1;
mdat_sem_post(&sem_arr[lChopstick]);
mdat_sem_post(&sem_arr[rChopstick]);
}
}
think();
}
}