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):
A thread uses the
EnterCriticalSection
orTryEnterCriticalSection
function to request ownership of a critical section. It uses theLeaveCriticalSection
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With