Sale!

ComS 352 Assignment 6

$30.00 $18.00

Category: You will Instantly receive a download link for .zip solution file upon Payment || To Order Original Work Click Custom Order?

Description

5/5 - (3 votes)

Run the following program in a linux system, and observe the behaviors of threads and particularly if the execution of critical sections interleave. Then, answer questions.

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
pthread_t tids[3];
int count=0;

void *th0(void *x)
{
printf(“Th0 starts.\n”);

/*following is a critical section —
as shared variable count is accessed*/
printf(“Th 0: Count=%d\n”, count);
count = count + 1;
sleep(1);
count = count – 1;
printf(“Th 0: Count is changed to %d\n”, count);
}

void *th1(void *x)
{
printf(“Th1 starts.\n”);

/*following is a critical section*/
printf(“Th 1: Count=%d\n”, count);
count = count + 2;
sleep(1);
count = count – 2;
printf(“Th 1: Count is changed to %d\n”, count);
}

void *th2(void *x)
{
printf(“Th2 starts.\n”);

/*following is a critical section*/
printf(“Th 2: Count=%d\n”, count);
count = count – 3;
sleep(1);
count = count + 3;
printf(“Th 2: Count is changed to %d\n”, count);
}

nt main()
{
pthread_create(tids,NULL,th0,NULL);
pthread_create(tids+1,NULL,th1,NULL);
pthread_create(tids+2,NULL,th2,NULL);
pthread_join(tids[0], NULL);
pthread_join(tids[1], NULL);
pthread_join(tids[2], NULL);
}

Questions:

1. Modify the program to ensure all threads execute their critical sections in a mutual exclusive manner, by using semaphore(s) provided by the POSIX semaphore library. List the modified program below. (30pts)

2. Based on the program modified in 1, change the program further to ensure thread th1 executes its critical section first, followed by th0 executing its critical section, and th2 is the last one executes its critical section. List the modified program below. (70pts)