1. (20 pts) Consider the following code example for allocating and releasing pro
ID: 3724814 • Letter: 1
Question
1. (20 pts) Consider the following code example for allocating and releasing processes(i.e., tracking number of #define MAX PROCS 255 nt numberofprocesses = 0; - - / the implementation of fork) calls this function / int allocate process) int new pid if (number-of-processes else [ MAX-PROCS) - return-1: /* allocate process resources and assign the PID to new-pid ++number_of_processes return new_pid: /* the implementation of exit void release_processo calls this function */ /* release process resources / -number_of_processes: a. (6 pts) Identify the race condition(s) b. (7 pts) Assume you have a mutex lock named mutex with the operations acquire and release). Please annotate the above code with acquire and release to prevent the race condition(s) c. (7 pts) Could we replace the integer variable int number-of-processes 0; = with the atomic integer atomic t number of processes 0 to prevent the race condition(s)? Why or why not? [note: this implies that one replaces any access to the atomic integer with the proper atomic operation atomic_operation, and you can assume all such atomic operations are available.]Explanation / Answer
a. Race condition in the given code is number_of_processes. Here both the methods allocate_process() and release_process() are using the variable number_of_processes. So there may be chance that one method is trying to access the variable while other method is modifying it. For example in this given code, let release_process() is decrementing the value of number_of_process and at the same time allocate_process() is accessing it. So there is a chance that it will return -1 indicating there is no process free. So in this way there is a race over number_of_processes.
b. Now we have a mutex lock names mutex with the operations acquire() and release(). The code will look like this
#define MAX_PROCS 255
int number_of_processes = 0;
/*the implementation of fork() calls this function */
int allocate_process() {
try{
lock.acquire();
int new_pid;
if( number_of_processes == MAX_PROCS)
return -1;
else {
/*allocate process resources and assign the PID to new_pid */
++ number_of_processes;
return new_pid;
}
}finally {
lock.release();
}
}
/* the implementation of exit() calls this function */
void release_process() {
try{
lock.acquire();
/* release process resources */
-- number_of_resources;
} finally {
lock.release();
}
}
c. No, just replacing the integer number_of_process with atomic number_of_process won't help to prevent race condition. As you can see that number_of_process is being refererred twice inside allocate_process itself. Once it is operated on by equality operator and second time by increment operator. So the whole allocate_process() is not atomic.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.