I was reading about mutex,semaphores and critical sections. I understand that mutex synchronizes a resource so that only one thread accesses it at a time a semaphore allows a specific no of threads to access a resource but what do critical sections do ??

- 449,505
- 63
- 781
- 982

- 11,179
- 26
- 86
- 158
-
Are you talking about Windows, or in general? – Steve Townsend May 04 '12 at 21:22
-
7Read this - http://en.wikipedia.org/wiki/Critical_section, and then come back with a more specific question if it still doesn't make sense. – Oliver Charlesworth May 04 '12 at 21:22
-
It seems to me from reading that wikipedia article that semaphores and critical sections are the same ? – Rajeshwar May 04 '12 at 21:36
-
No, they are not. Semaphores, in general, have a count. It is true that a semaphore initialized to 1 can be used to control a critical section, but there are still differences - a Windows Critical Secton canot be used for inter-process synch but can have a higher performance than a mutex/sema when used for inter-thread synchro. A CS allows recursive locking, a semaphore initialized to 1 will not. – Martin James May 04 '12 at 21:55
1 Answers
In normal use, a critical section is a section of code that must be executed serially -- i.e., only one thread can execute that code at any given time. You normally accomplish that by protecting the code with a mutex semaphore.
In Windows parlance, a critical section is a data structure (and a few associated functions) that implement at process-specific mutex semaphore (i.e., one that's used only for locking between threads in a single process, not between separate processes).
There are two varieties of semaphores. A mutex semaphore lets only one thread execute at a time. A counted semaphore lets you specify the maximum number of threads that can execute simultaneously. Mutex semaphores are the more common variety, but counted semaphores definitely have uses as well.

- 476,176
- 80
- 629
- 1,111
-
Is a "mutex semaphore" the same thing as a "binary semaphore" (there is a related [SO question](http://stackoverflow.com/questions/62814/difference-between-binary-semaphore-and-mutex))? The terminology can be confusing sometimes. – Jesse Good May 04 '12 at 22:08
-
2No, the two aren't quite the same. A locked mutex can only be unlocked by whoever previously locked it. A locked binary semaphore can be unlocked by anybody. – Jerry Coffin May 04 '12 at 22:12
-
Thanks, makes sense. However, that would lead me to believe there are three varieties of semaphores? (sorry to nitpick). – Jesse Good May 04 '12 at 22:19
-
@JesseGood: Depending on what level of detail you want to get into, there are still more -- for example, some mutexes are "recursive", meaning the same thread can claim ownership repeatedly, and retain it until it has released ownership the same number of times. Other mutexes will deadlock the thread if it tries to obtain ownership twice. – Jerry Coffin May 04 '12 at 22:29