Question

In: Computer Science

Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and...

Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period of time approximates the typical pid usage in which a pid is assigned to a new process, the process executes and then terminates, and the pid is released on the process's termination.) On UNIX and Linux systems, sleeping is accomplished through the sleep() COMP2004 Assignment 3 & Assignment 4 Fall 2020 function, which is passed an integer value representing the number of seconds to sleep.

HERE IS MY CODE:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MIN_PID 300
#define MAX_PID 5000

typedef struct node {
int pid;
struct node* next;
}Node;

int allocate_map(void);
int allocate_pid(void);
void release_pid(int pid);
int i;
Node *head;
/*
main function tests all three functions
*/
int main(){
allocate_map();
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
release_pid(301);
printf("allocated pid: %d\n",allocate_pid());
allocate_map();
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
release_pid(305);
release_pid(30);

}

int allocate_map(void){
if(i>0){
return -1;
}
head = malloc(sizeof(Node));
Node *curr = head;
for(i=0;i<MAX_PID-MIN_PID;i++){
curr->pid = 0;
curr->next = (i<(MAX_PID-MIN_PID)) ? malloc(sizeof(Node)):NULL;
curr = curr->next;
}

return 1;
}
int allocate_pid(void){
if(head->next == NULL){
return -1;
}

int i = MIN_PID +1 ;

Node *iter = head;
if(head->pid == 0){
head->pid = MIN_PID;
return head->pid;
}
while(iter ->next->pid !=0 && i<MAX_PID){
iter = iter->next;
i++;
}
if(i<MAX_PID ){

iter->next->pid = i;
return iter->next->pid;
}
else{return -1;}
}

void release_pid(int pid){
if(head->next == NULL && head->pid==0){
printf("Nothing to release\n");
return;
}
else if(pid<MIN_PID || pid>MAX_PID){
printf("invalid release\n");
return;
}
if(head->pid==pid){
head->pid=0;
}
Node *iter = head;
while(iter->next !=NULL){
if(iter->next->pid==pid){
iter->next->pid=0;
return;
}
iter = iter->next;
}
printf("Nothing to release\n");
}

Solutions

Expert Solution

*****make sure you  are running it on linux machine 
compile as >gcc pid.c -o pid -lpthread
run as     >./pid
*****/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
#include<pthread.h>
#include<semaphore.h>
#define MIN_PID 300
#define MAX_PID 5000
#define NUM_THREADS 100
#define YES 0
#define NO 1
sem_t SEM;

struct PidTable{
        int PID;
        int isAvailable;
}*pId;

int allocate_map(){
        int i;
        pId=(struct PidTable *)calloc((MAX_PID-MIN_PID+1),sizeof(struct PidTable));
        if(pId==NULL)
                return -1;
        pId[0].PID=MIN_PID;
        pId[0].isAvailable=YES;
        for( i=1;i<MAX_PID-MIN_PID+1;i++){
        pId[i].PID=pId[i-1].PID+1;
          pId[i].isAvailable=YES;
        }
        return 1;
}
int allocate_pid(){
   int i ;
   for( i=0;i<MAX_PID-MIN_PID+1;i++){
                if(pId[i].isAvailable==YES){
                        pId[i].isAvailable=NO;
                        return pId[i].PID;
                }
   }
        return -1;
}
void release_pid(int pid){
        pId[pid-MIN_PID].isAvailable=YES;
}


void *processStart(void *id){
        //long tid=(long)id;
        int pid,executionTime;
        sem_wait(&SEM);
        pid=allocate_pid();
        usleep(10000);
        sem_post(&SEM);
        if(pid!=-1){
                //printf("Thread %ld  runnning....\n",tid);
                printf("New Process Allocated Pid= %d \n",pid);
                executionTime=rand()%10;
                sleep(executionTime);
                printf("Process %d releasing pid \n",pid);
                release_pid(pid);
        }
        pthread_exit(NULL);
}
int main(){
  allocate_map();
  srand(time(NULL));
  void *status;int i;
  int ret=0;pthread_t thread[100];
  sem_init(&SEM,0,1);
  for(i=0;i<NUM_THREADS;i++){
        ret=pthread_create(&thread[i],NULL,processStart,(void *)(i+1));
        if(ret){printf("Error creating thread\n");exit(1);}
  }
  for(i=0; i<NUM_THREADS; i++) {
      ret = pthread_join(thread[i], &status);
      if (ret) {
         printf("ERROR; return code from pthread_join() is %d\n", ret);
         exit(-1);
         }
  }
  return 0;
}
OUTPUT:

Related Solutions

You will create a number of threads—for example, 100—and each thread will request a pid, sleep...
You will create a number of threads—for example, 100—and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period of time approximates the typical pid usage in which a pid is assigned to a new process, the process executes and then terminates, and the pid is released on the process's termination.) On UNIX and Linux systems, sleeping is accomplished through the sleep() function, which is passed an...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a CPU scheduler. The number of CPU’s and the list of processes and their info will be read from a text file. The output, of your simulator will display the execution of the processes on the different available CPU’s. The simulator should also display: -   The given info of each process -   CPU utilization - The average wait time - Turnaround time for each process...
Problem Write in drjava is fine. Using the classes from Assignment #2, do the following: Modify...
Problem Write in drjava is fine. Using the classes from Assignment #2, do the following: Modify the parent class (Plant) by adding the following abstract methods: a method to return the botanical (Latin) name of the plant a method that describes how the plant is used by humans (as food, to build houses, etc) Add a Vegetable class with a flavor variable (sweet, salty, tart, etc) and 2 methods that return the following information: list 2 dishes (meals) that the...
Problem Write in drjava is fine. Using the classes from Assignment #2, do the following: Modify...
Problem Write in drjava is fine. Using the classes from Assignment #2, do the following: Modify the parent class (Plant) by adding the following abstract methods: a method to return the botanical (Latin) name of the plant a method that describes how the plant is used by humans (as food, to build houses, etc) Add a Vegetable class with a flavor variable (sweet, salty, tart, etc) and 2 methods that return the following information: list 2 dishes (meals) that the...
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
*C PROGRAMMING* Create a program which requires the computer to guess the user's number from 1-100....
*C PROGRAMMING* Create a program which requires the computer to guess the user's number from 1-100. The user does not need to enter their number at any point. The computer should just guess a random number, and then the user can choose whether or not the number is too high or too low, and if the computer does not guess the correct number, it will will keep guessing and eliminate the values from the range that is either too high...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the InsufficientFundsException.java file is in the same folder as your User.java File. To test this program you will need to create your own "main" function which can import the User, create an instance and call its methods. One of the methods will throw an exception in a particular circumstance. This is a good reference for how throwing exceptions works in java. I would encourage you...
In this programming assignment, you need to create 3 files. 1. DateType.h 2. DateType.cpp 3. A...
In this programming assignment, you need to create 3 files. 1. DateType.h 2. DateType.cpp 3. A test driver for testing the class defined in the other 2 files. You can name your file in the way you like. Remember it must be a .cpp file. In DateType.h file, type these lines: // To declare a class for the Date ADT // This is the header file DateType.h class DateType { public: void Initialize(int newMonth, int newDay, int newYear); int GetYear()...
C++ Programming Chapter 7 Assignment: Assignment #4 – Student Ranking : In this assignment you are...
C++ Programming Chapter 7 Assignment: Assignment #4 – Student Ranking : In this assignment you are going to write a program that ask user number of students in a class and their names. Number of students are limited to 100 maximum. Then, it will ask for 3 test scores of each student. The program will calculate the average of test scores for each student and display with their names. Then, it will sort the averages in descending order and display...
1. Copy the files from Assignment 1 to Assignment 3. 2. Modify the PetFoodCompany header to...
1. Copy the files from Assignment 1 to Assignment 3. 2. Modify the PetFoodCompany header to mention a friend function called "computeBonusBudget". This method should compute the bonus budget as netIncome() * BonusBudgetRate and this method should exist in the driver program - not the Class defintion. 3. Modify the output of the program to display the results of the computeBonusBudget. Enter Total Sales: 1000 Enter Total Expenses: 600 Net Income = 400 Bonus Budget = 8 Here is the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT