views:

92

answers:

3
+1  Q: 

CriticalSection

hey,

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

A: 

These control structures stop the thread that can't enter from doing a busy wait by allowing it to sleep until an interrupt is generated by the thread that is in the critical section finishing execution. Because the thread is asleep it is not using processor cycles, so no busy_wait.

tloach
+1  A: 

The thread is not going to be taking any system resources, because it will be marked as "waiting". As soon as the thread occupying the critical region finishes, it will send out a signal that will move the waiting thread to the ready queue.

dhorn
+2  A: 

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.

Michael
ok, but that's true when the EnterCriticalSection wait infinite time for the critical section to be released.what happens if i set time limit of 5 second, the function should return after 5 seconds. so if the thread is not on the ready queue, and the thread owning the critical section hasn't released the CT, the thread won't return after 5 seconds. what happens then ?
Idan
The thread enters a wait on two different objects - the kernel event that backs the critical section and a timer object that expires after 5 seconds. If either becomes "signaled" then the thread moves back into the ready queue.
Michael
Awesome! thanks
Idan