Create a single dimensional array between 10 and 1000 entries to represent seats
ID: 3699911 • Letter: C
Question
Create a single dimensional array between 10 and 1000 entries to represent seats in the theater. Initialize all valuables to "A" for available. Create a function named agent that will be changing the available seats to "S" for sold. Multiple threads of the "agent" function will be working concurrently on the exact same array., and all threads will end once all seats have been sold (all values set to "S").
This Homework will require the use of process.h and semaphore.h, which we will use to create threads and avoid race conditions, respectively.
ALL OF THIS TO BE DONE IN C.
Explanation / Answer
// C program to demonstrate working of Semaphores
//Note: compile code by cc filename.c -pthread
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
void creatThread();
#define SEAT_NO 25 //change it as per your requirement
sem_t mutex;
char seats[SEAT_NO];
int count = 0;
/*
Thread fuction which will be used by many threads to reserve the seat
*/
void* agent(void* arg)
{
sleep(random()%5); //creating random sleep to examin race condition
// checking avablity of resource , if semaphore is not availble then wait for to make it available
sem_wait(&mutex);
// checking that count shoud not reach to the max value(to protect from segmentation fault)
if(count < SEAT_NO )
{
// Reserving the seat if it is not reserved
if (seats[count] != 'S')
seats[count] = 'S';
}
count++;
sem_post(&mutex);
}
int main()
{
creatThread();
return 0;
}
void creatThread()
{
int i;
// setting seats as an available
for(i=0;i<SEAT_NO;i++)
seats[i] = 'A';
// initing semaphore
sem_init(&mutex, 0, 1);
pthread_t t[SEAT_NO];
// creat multiple thread to reserve seat
for(i=0;i<SEAT_NO;i++)
{
pthread_create(&t[i],NULL,agent,NULL);
}
// join to the tread if exit
for(i=0;i<SEAT_NO;i++)
pthread_join(t[i],NULL);
//delete mutex
sem_destroy(&mutex);
printf("seat status: ");
//printing seat value
for(i=0;i<SEAT_NO;i++)
{
printf("%c ",seats[i]);
if(!((i+1)%5))
printf(" ");
}
printf(" ");
}
//expected output:
/*
seat status:
S S S S S
S S S S S
S S S S S
S S S S S
S S S S S
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.