Question: Write a multithreaded program that tests your solution to the code below. You will create several threads for example, 100 and each thread will request
Write a multithreaded program that tests your solution to the code below. 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.
public class PIDHW1 { public static void main(String[] args) { allocate_map(); for (int i = 0; i < 51; i++) System.out.println(allocate_pid()); release_pid(315); release_pid(320); release_pid(309); release_pid(304); System.out.println(); System.out.println(allocate_pid()); System.out.println(allocate_pid()); System.out.println(allocate_pid()); System.out.println(allocate_pid()); System.out.println(allocate_pid()); }
// Declaring constant variables to set our range static int MIN_PID = 300; static int MAX_PID = 5000; static int bytesRequired = (int) Math.ceil((MAX_PID - MIN_PID + 1.0) / 8); static byte processMap[];
// Creating byte array to represent bytes static int allocate_map() { processMap = new byte[bytesRequired]; for (int i = 0; i < bytesRequired; i++) processMap[i] = 0; return 1; }
// Method to allocate space for pid static int allocate_pid() { int pos, i; for (pos = 0; pos < bytesRequired; pos++) if (processMap[pos] != -1) break;
if (pos == bytesRequired) return -1; // Returns -1 if there is no space available for (i = 0; i < 8; i++) if ((processMap[pos] & (1 << i)) == 0) { if (MIN_PID + pos * 8 + i > MAX_PID) return -1; processMap[pos] |= (1 << i); return MIN_PID + pos * 8 + i; }
return -1; }
// Frees space by releasing a pid static void release_pid(int pid) { if ((pid < MIN_PID) || (pid > MAX_PID)) return; int pos = (pid - MIN_PID) / 8; int i = pid - MIN_PID - pos * 8; processMap[pos] &= ~(1 << i); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
