Consider the following three threads and four semaphores Consider the following
ID: 3823796 • Letter: C
Question
Consider the following three threads and four semaphores
Consider the following three threads and four semaphores/Star Initialize X Star/X = 1;/Star Initialize semaphores Star/s1 = s2 = s3 = s4 = void thread1 () {while (x ! = 360) {x = x Star 2;} exit (0);} void thread2 () {while (x ! = 360) {x = x Star 3;} exit (0);} void thread3 () {while (x ! = 360) {x = x Star 5;} exit (0);} Provide initial values for the four semaphores and add P(), V() semaphore operations (using the four semaphores) in the code for thread 1, 2 and 3 such that the process is guaranteed to terminate.Explanation / Answer
/* Initialize x */
x = 1;
// Semaphores are initialized with the following values
// These are binary semaphores
s1 = 1;
s2 = 1;
s3 = 0;
s4 = 0;
//Thread 1 starts executing
void thread1(){
while(x != 360){
P(s1);
x = x * 2;
V(s3);
}
}
void thread2(){
while(x != 360){
P(s3);
P(s2);
x = x * 3;
V(s1);
V(s4);
}
}
void thread3(){
while(x != 360){
P(s4);
x = x * 5;
V(s2);
}
}
P() locks the resources
V() releases the resources
Explanation of the code:
1) Start with thread1 -> Lock s1 -> x=2(1*2) -> Release s3
2) Thread2 -> Lock s3,s2 -> x=6(2*3) -> Release s1,s4
Note- As s1 released first so thread1 started first instead of thread3
3) Thread1 -> Lock s1 -> x=12(6*2) -> Release s3
4) Thread3 -> Lock s4 -> x=60(12*5) -> Release s2
5) Thread2 -> Lock s3,s2 -> x=180(60*3) -> Release s1,s4
6) Thread1 -> Lock s1 -> x=360(180*2) -> Release s3
7) x != 360 Condition fails. All threads terminates.