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...
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...
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...
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...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
CS 1102 Unit 5 – Programming AssignmentIn this assignment, you will again modify your Quiz program...
CS 1102 Unit 5 – Programming AssignmentIn this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the full...
Modify the following source code so that five subsequent threads print the message “Hello World number,”...
Modify the following source code so that five subsequent threads print the message “Hello World number,” where number indicates the unique thread created; e.g. “Hello World 1” // Your_name_goes_here #include <pthread.h> #include <semaphore.h> sem_t semaphore; // also a global variable just like mutexes void *thread_function( void *arg ) { sem_wait( &semaphore ); // perform some task pthread_exit( NULL ); } int main() { int tmp; tmp = sem_init( &semaphore, 0, 0 ); // initialize pthread_create( &thread[i], NULL, thread_function, NULL );...
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will...
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will use the concept of object aggregation (i.e., has-a relationship between objects). You will implement a Java application, called MovieApplication that could be used in the movie industry. You are asked to implement three classes: Movie, Distributor, and MovieDriver. Each of these classes is described below. The Movie class represents a movie and has the following attributes: name (of type String), directorsName (of type String),...
Java Programming In this assignment we are going to create our own programming language, and process...
Java Programming In this assignment we are going to create our own programming language, and process it Java. programming language has 6 commands enter add subtract multiply divide return enter, add, subtract, multiply, divide all take 1 parameter (a double value). return takes no parameters.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT