Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN C LANGUAGE AND THE EXPLANTION PLEASE!!! Using_beginthread spawn subprocesses

ID: 3801676 • Letter: I

Question

IN C LANGUAGE

AND THE EXPLANTION PLEASE!!!

Using_beginthread spawn subprocesses that sell pretend tickets to a show. The tickets correspond to slots in an array call it tickets. If ticket[i] == 1 it means that the ticket is available. If you sell that ticket change the value of ticket[j] to 0. To do this create a function called sell tickets that takes as input an array of tickets and returns a 0 if it sold a ticket or a 1 if there are no tickets left. Just before the return print that the handle sold a ticket. Since the array is a location in memory to be shared by the spawned processes you need to use the wait and signal functions to control access to the array. Read about them and then deploy them in your program.

Explanation / Answer

tickets.c

compile : gcc tickets.c -lpthread

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<pthread.h>
#include <semaphore.h>
#include<string.h>
//No of tickets
#define N 10
//No of processes
#define MAXTHREAD 10

int tickets[N];
int count=0;
static sem_t x;
int tindex=0;
void* sellTickets(void*arg)
{
   int id = *(int*)arg;
  
  
    while(1)
   {
     wait(x);

     //srand (time(NULL));
     //int index=rand() % N;

     if(count==N)
     {
       printf("No tickets are available ");  
  
     }
     else if(tickets[tindex]==1)
     {
        tickets[tindex++]=0;
        printf(" The ticket no %d is sold to the %d process ",tindex,id);
        count++;
    
      }
      else
        printf("Ticket no %d is not available for the process %d.It is already sold ",tindex,id);
      signal(x);     
          
   }


}


int main(int argc,char **argv)
{

   pthread_t process[100];
   int ids[MAXTHREAD];
   int index;
   for(int i=0;i<N;i++)
      tickets[i]=1;


if (sem_init(&x, 0, 1) == -1)
{
    printf("Error, init semaphore ");
    exit(1);
}

   for(index=0;index<MAXTHREAD;index++)
{
    ids[index]=index+1;
                        
    if(pthread_create(&process[index],0,sellTickets,&ids[index])!=0)
    {
       perror("Cannot create process! ");
       exit(1);                          
    }
}

return 0;
}