Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entering critical section and context switching in c++

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 ^_^

like image 278
M.R.M Avatar asked Oct 03 '22 15:10

M.R.M


1 Answers

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

  • MSDN: Using Critical Section Objects
  • Wikipedia: Critical Section
like image 52
Jonathon Reinhart Avatar answered Oct 12 '22 15:10

Jonathon Reinhart