What are Critical sections in threads
Asked Answered
M

1

8

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 ??

Micelle answered 4/5, 2012 at 21:21 Comment(4)
Are you talking about Windows, or in general?Borrow
Read this - en.wikipedia.org/wiki/Critical_section, and then come back with a more specific question if it still doesn't make sense.Lollis
It seems to me from reading that wikipedia article that semaphores and critical sections are the same ?Micelle
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.Heterosexuality
S
16

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.

Signatory answered 4/5, 2012 at 21:43 Comment(4)
Is a "mutex semaphore" the same thing as a "binary semaphore" (there is a related SO question)? The terminology can be confusing sometimes.Agnostic
No, 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.Signatory
Thanks, makes sense. However, that would lead me to believe there are three varieties of semaphores? (sorry to nitpick).Agnostic
@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.Signatory

© 2022 - 2024 — McMap. All rights reserved.