Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can context switch take place while in a critical section?

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?

like image 822
user358789 Avatar asked Jun 23 '10 16:06

user358789


People also ask

Can a context switch occur in a critical section?

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.

Under which conditions does a context switch take place?

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.

Which is the situation under which context switching will not be done?

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 does context switch happen?

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.


1 Answers

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.)

like image 72
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet