You're just a user-mode process, you can't prevent the OS from context switching to another process. What it means is no other thread in your process can enter the critical section until the first thread leaves it.
From MSDN (emphasis mine):
A thread uses the EnterCriticalSection
or TryEnterCriticalSection
function to request ownership of a critical section. It uses the LeaveCriticalSection
function to release ownership of a critical section. If the critical section object is currently owned by another thread, EnterCriticalSection
waits indefinitely for ownership.
And again, EnterCriticalSection
says:
Waits for ownership of the specified critical section object. The function returns when the calling thread is granted ownership.
To answer the question of "will this prevent context switching between threads". No. Well, not really. Say you have two threads, A and B. A calls EnterCriticalSection
and enters the CS. While he is using the shared resource in the CS, the OS can still context switch to thread B. B will continue to run as he did before, until he gets to the EnterCriticalSection
call, at which point he will block.
Now how this blocking is implemented really up to Windows. But most likely, instead of "spinning" (Can I enter? No. Now? No. Now? No.) the OS will put that thread on "blocked" queue, and not schedule the thread until the thing he is waiting on (the CS) is available. At that point, he will be scheduled, and the call to EnterCriticalSection
will succeed.
See also