views:

47

answers:

2

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?

+4  A: 

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

Jon Skeet
+1  A: 

It depends on what version of a "critical section" you're dealing with. Just for example, in OS/2 (the predecessor to current Windows that first included critical sections) entering a critical section prevented switching to a different thread in the same process. In Windows NT, they changed that so thread switching is allowed, so other threads will only be blocked when/if they attempt to enter the same critical section.

In both these cases, a critical section is local to a process so a thread in a different process can never attempt to enter the same critical section.

On other systems, you'll have to look at how a critical section (assuming it has one) is specified to know what it allows/prohibits. There's no universal definition.

Jerry Coffin