What are Critical sections in threads

Rajeshwar picture Rajeshwar · May 4, 2012 · Viewed 16.1k times · Source

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

Answer

Jerry Coffin picture Jerry Coffin · May 4, 2012

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.