Is is the right way to use critical section
---------------------------------------------------------------------------
void main()
{
CRITICAL_SECTION testsection;
InitializeCriticalSection(&testsection);
....
}
void Thread()
{
EnterCriticalSection(&testsection);
....
LeaveCriticalSection(&testsection);
}
----------------------------------------------------------------------------
For some reason it is not blocking before the entercriticalsection. For example,
if I tried :
EnterCriticalSection(&testsection);
TRACE(" step 1\n");
EnterCriticalSection(&testsection);
TRACE(" step 2\n");
I would see :
step 1
step 2
Shouldn't the thread block on the 2nd EnterCriticalSection I think it must be something really obvious I'm doing wrong but can't figure it out.

Help, critical section doesn't seem to work
808
No they are no separate threads. As long as the windows are created in one thread they belong to this thread. Look at the code how the create the other top level windows. Its just from the thread that executes "File new".
Its just one big GUI main thread that handles all those windows. You can see that when AfxMessageBox is called from one main window. The other gets blocked to!
bigman921
No. A single thread can enter a CRITICAL_SECTION as many times as it wants. A counter is just incremented in the CRITICAL_SECTION structure. Note that you must have a matching LeaveCriticalSection for every EnterCriticalSection before another thread would be allowed to enter the CRITICAL_SECTION.
Joshua Cole
I tried an experiment that I assign a critical section member variable for the WinApp class that is common to all top level windows (since there is only one WinApp active at one time) and let each of the new top-level views created get access to the critical section variable by the AfxGetApp() function.
In debug mode, I can see the lockcount went from -1 to 0 after the 1st top level window that access EnterCriticalSection. I force the 1st window to not call LeaveCriticalSection. When the 2nd top level window access EnterCriticalSection it sees that the lockcount is 0 and still didn't block. (the 2nd window increament the lockcount to 2 and step right through the EnterCriticalSection statement)
According to your explaination, this means that both top level windows are behaving like the same thread I think I'm missing something here....
alfeliche
I'm seeing one definition of testsection, and it is local to main. Do you have another definition of testsection sitting around somewhere
There's a nice simple C++ wrapper for critical sections in stllock.h, part of the Platform SDK headers.
Define globally:
CCritSec myCritSec;
And then guard the functions and/or data that are accessed by multiple threads by entering and leaving it:
myCritSec.Enter()
myCritSec.Leave()
I wrote a second class that wraps these two operations: its constructor (which takes a reference to the CCritSec) enters the CS and its destructor leaves it. This makes it both convenient and safe.
Brian