Recently I read an interesting blog comparing mutex and semaphore:
"
http://www.feabhas.com/blog/2009/09/mutex-vs-semaphores-%E2%80%93-part-1-semaphores/
"
Quote from it:
"
If a context switch happens while that task is in the critical region, and another task also calls on P(S), then that second task (and any subsequent tasks) will be blocked from entering the critical region by being put in a waiting state by the operating system. At a later point the first task is rescheduled and calls V(S) to indicate it has left the critical region. The second task will now be allowed access to the critical region.
"
If this is true for semaphore, is it also true for mutex? I don't think it's true as if a block of code is locked, it should be "atomic" that cannot be context switched out or interrupted. Am I right?
If a context switch happens while that task is in the critical region, and another task also calls on P(S), then that second task (and any subsequent tasks) will be blocked from entering the critical region by being put in a waiting state by the operating system.
A context switch occurs when the kernel transfers control of the CPU from an executing process to another that is ready to run. The kernel first saves the context of the process.
Time is required to save the context of one process that is in the running state and then getting the context of another process that is about to come in the running state. During that time, there is no useful work done by the CPU from the user perspective. So, context switching is pure overhead in this condition.
How often Windows context switches depends on the system "quantum". This quantum ranges from 10-15 milliseconds (66-100 times per second) depending on whether the OS is client or server.
No, a context switch can happen almost anywhere. While it's generally a good idea to hold locks for as brief a time as possible, you wouldn't want your entire machine to lock just because one process had as many threads holding locks as there are cores, waiting for something to happen, would you?
The point of a lock is to prevent code which might interfere with the code in the lock from being executed - it's not to stop all other code from being executed, in every process in the system. (A context switch to a different process is still a context switch, after all.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With