I am trying to understand how the code below works. This is straight out of my profs lecture slides. This P() and V() function is the part of semaphore implementation in the OS that we use in class (OS161). I think you might need understanding of the OS161 to answer my question, since its widely used, hopefully some one can answer this questions.
My understanding of this code with lecture notes:
X:Flow of the P() function
1. When a thread call P(), we disable interrupt
2. check if we have any resources available on sem->count
3.a) if count is 0 then we go to sleep
3.b) if count != 0 then we decrements count and allow the calling thread to continue to critical section
4. Enable Interrupt
Y:Flow of the V() function
1. When a thread call V(), we disable interrupt
2. Increment the counter, implying that now there is 1 more resource available to grab
3. Now we go ahead and wake up all the thread that we sent to sleep in P(), because there was not enough resources available at the time the thread tried to grab a lock to a critical section
4. Enable Interrupt
My Problems:
1. Does "disable interrupt" section disable interrupt on a particular thread or does it disable all the interrupts?
2. On V() function when we wake up all the threads, the thread slept inside the while loop in P() function start to execute the while loop. In the lecture it says one thread grab the lock and rest go back to sleep. My question is why "sem->count == 0" condition doesn't evaluate to false to other threads but only one.
I really want to know how does the interrupt disable part works. which is my first question. Does it stops thread scheduler?, does it stop context switch in the system?
Why does the thread goes to sleep with interrupt disable? isn't that dangerous, since it can miss I/O finished signals and other things?
P(sem) {
Disable interrupts;
while (sem->count == 0) {
thread_sleep(sem); /* current thread
will sleep on this sem */
}
sem->count--;
Enable interrupts;
}
V(sem) {
Disable interrupts;
sem->count++;
thread_wakeup (sem); /* this will wake
up all the threads waiting on this
sem. Why wake up all threads? */
Enable interrupts;
}
Thank you.