When implementing a spin on a certain condition I use Sleep(0) inside the while loop to yield the processor in case the condition is not satisfied. The problem with this is that I have no idea to which thread I'm giving control and also when my thread will be rescheduled. I've found SwitchToThread() to be an alternative and from what I understand, the calling thread will only yield to same or higher priority threads and it will also be immediately rescheduled. Unfortunately, documentation on this function seems to be very scarce on the internet. Does anyone have more information about it?
The SwitchToThread from my experience (from behavior of programs) appears to work as follows
Each hardware thread (number of cores or number of cores * TH threads/core) has at most one running thread, a list of threads that have been pre-empted or absolutely everyting was completed to make the thread runable. In addition to these threads, there is a list of runable but not quite yet absolutely everyting was completed to make the thread runable. examples later.
The SwitchToThread() places the running thread at the end of the absolutely everything was completed to make the thread runnable list for that hardware thread. But in front of runnable but not quite yet absolutely everything was completed to make the thread runnable.
What I have observed is. A thread that experiences a page fault will get context switched out (put to sleep) or rescheduled and put to use to perform the paging operation. This thread (or other thread run by OS to do paging) is set into the runnable but not quite yet absolutely everything was completed to make the thread runnable list.
What this means is software threads performing SwitchToThread will have higher priority than those other threads.
Therefore, with over subscription (by all software threads of all applications) it is possible to have a collection of threads issuing SwitchToThread on all hardware threads while waiting for a resource held by a thread that may be runnable but has not yet made it into the run state. This will cause an interlocked condition.
You can also experience thisinterlock condition if threads are pinned to a logical processor and the running thread issues a SwitchToThread while the thread holding the resource came off a wait condition (e.g. paging or I/O, or WaitForSingleOgject, ...).
Arecommended work around is after n number of SwitchToThread() calls perform a Sleep(0) or whatever is your choice.