183k views
1 vote
Write a multithreaded program that tests your solution to HW#1. You will create several 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 approximates the typical pid usage in which a pid is assigned to a new process, the process executes and terminates, and the pid is released on the process’ termination). On UNIX and Linux systems, sleeping is accomplished through the sleep() function, which is passed an integer value representing the number of seconds to sleep.

User Radhi
by
5.7k points

1 Answer

5 votes

Answer:

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

#define MIN_PID 300

#define MAX_PID 5000

#define CB CHAR_BIT

int sz = MAX_PID - MIN_PID + 1;

unsigned char *unsignedChar;

int allocate_map();

int allocate_pid();

void release_pid(int pid);

int main()

{

int map = allocate_map();

if (map == 1) {

printf("\\Bitmap Data Structure initialized.\\");

int id = 0, i = 0;

//create 100 processes

while (i < 100) {

int val = allocate_pid();

printf("\\Process %d: pid = %d", i+1, val);

i++;

}

//release a few processes

release_pid(303); printf("\\Process 303 released.");

release_pid(308); printf("\\Process 308 released.");

release_pid(309); printf("\\Process 309 released.");

//allocate a few more processes after this release

int val = allocate_pid(); printf("\\Process %d : pid = %d", ++i, val); //should be 303

val = allocate_pid(); printf("\\Process %d : pid = %d\\", ++i, val); //should be 308

}

else printf("\\Failed to initialize data structure.\\");

}

/* Creates and initializes a bitmap data structure for representing pids;

returns —1 for unsuccessful, 1 for successful */

int allocate_map() {

unsignedChar = (unsigned char*)malloc((sz+CB-1)/CB * sizeof(char));

if (unsignedChar) return 1;

return -1;

}

/* Allocates and returns a pid; returns -1

if it is unable to allocate a pid (all pids are in use) */

int allocate_pid() {

int i = 0;

int pid = unsignedChar[i/CB] & (1 << (i & (CB-1)));

while (pid != 0) {

i++;

pid = unsignedChar[i/CB] & (1 << (i & (CB-1)));

}

if (i+MIN_PID > MAX_PID) return -1;

unsignedChar[i/CB] |= 1 << (i & (CB-1));

return i+MIN_PID;

}

/* Releases a pid given a pid parameter*/

void release_pid(int pid) {

if (pid < 300) {

printf("\\Invalid PID: It should lie between 300 and 3000.");

return;

}

int i = pid - MIN_PID;

unsignedChar[i/CB] &= ~(1 << (i & (CB-1)));

}

User Rtist
by
7.3k points