Question

In: Computer Science

Write program in C language using Pthreads API to simulate the real problem, the Sleeping Teaching...

  1. Write program in C language using Pthreads API to simulate the real problem, the Sleeping Teaching Assistant, using what we have studied IPC and synchronization. Refer to Section 5.9.4 for specific instructions on mutex lock and semaphore.
  2. If there are multiple files in your submission, you need to provide a makefile.
  3. Include the compilation command with required options at the very beginning of your code.

he Sleeping Teaching AssistantA university computer science department has a teaching assistant (TA) whohelps undergraduate students with their programming assignments duringregular ofFce hours. The TA’s ofFce is rather small and has room for only onedesk with a chair and computer. There are three chairs in the hallway outsidethe ofFce where students can sit and wait if the TA is currently helping anotherstudent. When there are no students who need help during ofFce hours, theTA sits at the desk and takes a nap. If a student arrives during ofFce hoursand Fnds the TA sleeping, the student must awaken the TA to ask for help. If astudent arrives and Fnds the TA currently helping another student, the studentsits on one of the chairs in the hallway and waits. If no chairs are available, thestudent will come back at a later time

Solutions

Expert Solution

#include <pthread.h>       //Create POSIX threads.
#include <time.h>           //Wait for a random time.
#include <unistd.h>           //Thread calls sleep for specified number of seconds.
#include <semaphore.h>       //To create semaphores
#include <stdlib.h>          
#include <stdio.h>           //Input Output

pthread_t *Students;       //N threads running as Students.
pthread_t TA;               //Separate Thread for TA.

int ChairsCount = 0;
int CurrentIndex = 0;

//Declaration of Semaphores and Mutex Lock.
sem_t TA_Sleep;
sem_t Student_Sem;
sem_t ChairsSem[3];
pthread_mutex_t ChairAccess;

//Declared Functions
void *TA_Activity();
void *Student_Activity(void *threadID);

int main(int argc, char* argv[])
{
   int number_of_students;       //a variable taken from the user to create student threads.   Default is 5 student threads.
   int id;
   srand(time(NULL));

   //Initializing Mutex Lock and Semaphores.
   sem_init(&TA_Sleep, 0, 0);
   sem_init(&Student_Sem, 0, 0);
   for(id = 0; id < 3; ++id)           //Chairs array of 3 semaphores.
       sem_init(&ChairsSem[id], 0, 0);

   pthread_mutex_init(&ChairAccess, NULL);
  
   if(argc<2)
   {
       printf("Number of Students not specified. Using default (5) students.\n");
       number_of_students = 5;
   }
   else
   {
       printf("Number of Students specified. Creating %d threads.\n", number_of_students);
       number_of_students = atoi(argv[1]);
   }
      
   //Allocate memory for Students
   Students = (pthread_t*) malloc(sizeof(pthread_t)*number_of_students);

   //Creating TA thread and N Student threads.
   pthread_create(&TA, NULL, TA_Activity, NULL);  
   for(id = 0; id < number_of_students; id++)
       pthread_create(&Students[id], NULL, Student_Activity,(void*) (long)id);

   //Waiting for TA thread and N Student threads.
   pthread_join(TA, NULL);
   for(id = 0; id < number_of_students; id++)
       pthread_join(Students[id], NULL);

   //Free allocated memory
   free(Students);
   return 0;
}

void *TA_Activity()
{
   while(1)
   {
       sem_wait(&TA_Sleep);       //TA is currently sleeping.
       printf("~~~~~~~~~~~~~~~~~~~~~TA has been awakened by a student.~~~~~~~~~~~~~~~~~~~~~\n");

       while(1)
       {
           // lock
           pthread_mutex_lock(&ChairAccess);
           if(ChairsCount == 0)
           {
               //if chairs are empty, break the loop.
               pthread_mutex_unlock(&ChairAccess);
               break;
           }
           //TA gets next student on chair.
           sem_post(&ChairsSem[CurrentIndex]);
           ChairsCount--;
           printf("Student left his/her chair. Remaining Chairs %d\n", 3 - ChairsCount);
           CurrentIndex = (CurrentIndex + 1) % 3;
           pthread_mutex_unlock(&ChairAccess);
           // unlock

           printf("\t TA is currently helping the student.\n");
           sleep(5);
           sem_post(&Student_Sem);
           usleep(1000);
       }
   }
}

void *Student_Activity(void *threadID)
{
   int ProgrammingTime;

   while(1)
   {
       printf("Student %ld is doing programming assignment.\n", (long)threadID);
       ProgrammingTime = rand() % 10 + 1;
       sleep(ProgrammingTime);       //Sleep for a random time period.

       printf("Student %ld needs help from the TA\n", (long)threadID);
      
       pthread_mutex_lock(&ChairAccess);
       int count = ChairsCount;
       pthread_mutex_unlock(&ChairAccess);

       if(count < 3)       //Student tried to sit on a chair.
       {
           if(count == 0)       //If student sits on first empty chair, wake up the TA.
               sem_post(&TA_Sleep);
           else
               printf("Student %ld sat on a chair waiting for the TA to finish. \n", (long)threadID);

           // lock
           pthread_mutex_lock(&ChairAccess);
           int index = (CurrentIndex + ChairsCount) % 3;
           ChairsCount++;
           printf("Student sat on chair.Chairs Remaining: %d\n", 3 - ChairsCount);
           pthread_mutex_unlock(&ChairAccess);
           // unlock

           sem_wait(&ChairsSem[index]);       //Student leaves his/her chair.
           printf("\t Student %ld is getting help from the TA. \n", (long)threadID);
           sem_wait(&Student_Sem);       //Student waits to go next.
           printf("Student %ld left TA room.\n",(long)threadID);
       }
       else
           printf("Student %ld will return at another time. \n", (long)threadID);
           //If student didn't find any chair to sit on.
   }
}


Related Solutions

Programming Language: C++ Overview For this assignment, write a program that will simulate a single game...
Programming Language: C++ Overview For this assignment, write a program that will simulate a single game of Craps. Craps is a game of chance where a player (the shooter) will roll 2 six-sided dice. The sum of the dice will determine whether the player (and anyone that has placed a bet) wins immediately, loses immediately, or if the game continues. If the sum of the first roll of the dice is equal to 7 or 11, the player wins immediately....
(using C in a Linux environment and the POSIX pthreads library) Write a program named Sort.c...
(using C in a Linux environment and the POSIX pthreads library) Write a program named Sort.c that accepts a list of numbers from the user. There are two threads: Main thread waits for the numbers to be entered by the user and for the second thread to finish sorting. It then asks user whether there are more lists or not. It will do this until the user indicates there are no more lists to be entered, at which point it...
please write in c using linux or unix Write a program that will simulate non -...
please write in c using linux or unix Write a program that will simulate non - preemptive process scheduling algorithm: First Come – First Serve Your program should input the information necessary for the calculation of average turnaround time including: Time required for a job execution; Arrival time; The output of the program should include: starting and terminating time for each job, turnaround time for each job, average turnaround time. Step 1: generate the input data (totally 10 jobs) and...
Please write in C using linux or unix. Write a program that will simulate non -...
Please write in C using linux or unix. Write a program that will simulate non - preemptive process scheduling algorithm: First Come – First Serve Your program should input the information necessary for the calculation of average turnaround time including: Time required for a job execution; Arrival time; The output of the program should include: starting and terminating time for each job, turnaround time for each job, average turnaround time. Step 1: generate the input data (totally 10 jobs) and...
Write a C or C++ program that uses pthreads to compute the number of values that...
Write a C or C++ program that uses pthreads to compute the number of values that are evenly divisible by 97 between a specified range of values (INCLUSIVE). The program should accept 3 command-line arguments: low value high value number of threads to create to perform the computation -Specifics for program order of input: 0 9000000000 2 this means 0 to 9 Billion (INCLUSIVE); 2 threads alarm(90); this should be the first executable line of the program to make sure...
Use any C program without using PTHREADS calculate time taken to execute program. Write same program...
Use any C program without using PTHREADS calculate time taken to execute program. Write same program of question 1 using PTHREADS. Calculate time taken to execute program.(1 mark) Identify data races in above program and explain why this situation occurred with an example (1 mark) Rewrite the code to avoid data races should use any of the THREE techniques.(1.5 marks) please I need the c code.. critical section mutex solution semaphore functions Barriers Read-Write Locks Run program using 1, 2,...
Use any C program without using PTHREADS calculate time taken to execute program. Write same program...
Use any C program without using PTHREADS calculate time taken to execute program. Write same program of question 1 using PTHREADS. Calculate time taken to execute program. Identify data races in above program and explain why this situation occurred with an example Rewrite the code to avoid data races should use any of the THREE techniques. critical section mutex solution semaphore functions Barriers Read-Write Locks Run program using 1, 2, 4, and 8 threads Comparison study Number of threads Implementation...
Write a Pthreads program 'Dining-Philosophers.c' to implement the classical 'Dining-Philosophers'problem by using Pthreads mutex locks and...
Write a Pthreads program 'Dining-Philosophers.c' to implement the classical 'Dining-Philosophers'problem by using Pthreads mutex locks and condition variables. To implement the program, please followthe hints below. (a) The detailed 'Dining-Philosophers' problem statement: Refer to Page 71 ~ Page 72 in 'Lecture-08.pptx'    (b) The introduction to Pthreads mutex locks and condition variables: Refer to Page 17 ~ Page 39 in'Lecture-08.pptx'    (c) Creating five philosophers, each of which will run as a separate thread. Philosophers alternatebetween thinking and eating: The activities...
Write a program to simulate the Distributed Mutual Exclusion in ‘C’.
Write a program to simulate the Distributed Mutual Exclusion in ‘C’.
Using C language: Write a program that asks the user for the size of an array,...
Using C language: Write a program that asks the user for the size of an array, then reads a number of integer values (from user input) into the array. Write a function to print out the array and call it to print the array out after all values are read in. Write a function to implement Insertion Sort and run it on the data array to sort the array. Write another function to implement Selection Sort and run it on...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT