I'm new to thread programming (currently need to use win32 and c++ in a company project) and I just want to ask does entering the critical section means no context switching? does it mean that the thread will lock the resources until it leaves the critical section?
Also, I'm currently reading "Multithreading Applications in Win32" book and it seems good but is there a better-to-read and more up-to-date book for newbies to learn threading in win32?
Many thanks in advance ^_^
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):
And again,
EnterCriticalSection
says: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 theEnterCriticalSection
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