Search code examples
critical-section

CriticalSection


i'm not sure about something.

when i use critical_section/mutex/semaphor in c++ for example , how does the busy_wait problem being prevented ?

what i mean is when a thread reaches a critical section and the critical section is occupied by other thread, what prevents the thread from wasting cycle time and wait for nothing ?

for example, should i call TryEnterCriticalSection and check if the thread obtained ownership and otherwise call sleep(0) ?

i'm a bit perplexed

thanks


Solution

  • This is Windows specific, but Linux will be similar.

    Windows has the concept of a ready queue of threads. These are threads that are ready to run, and will be run at some point on an available processor. Which threads are selected to run immediately is a bit complicated - threads can have different priorities, their priorities can be temporarily boosted, etc.

    When a thread waits on a synchronization primitive like a CRITICAL_SECTION or mutex, it is not placed on the ready queue - Windows will not even attempt to run the thread and will run other threads if possible. At some point the thread will be moved back to the ready queue, for instance when the thread owning the CS or mutex releases it.