EnterCriticalSection doesn't seem to block
I have the following code to create threads to do some work (with details omitted for clarity).
CRITICAL_SECTION gCS;
class Locker
{
public:
Locker(CRITICAL_SECTION& cs): m_cs(cs)
{
EnterCriticalSection(&m_cs);
}
~Locker()
{
LeaveCriticalSection(&m_cs);
}
private:
CRITICAL_SECTION m_cs;
};
...
HRESULT MyClass::FinalConstruct()
{
InitializeCriticalSection(&gCS);
}
...
DWORD WINAPI MyClass::CreateThread()
{
hWriteReceiptThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyClass::RunThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
return 0;
}
DWORD WINAPI MyClass::RunThread(LPVOID args)
{
{
LogInfo("getting lock for critical Section");
Locker lock(gCS);
EnterCriticalSection(&gCS);
LogInfo("entered Critical Section");
//... do lots of stuff
LogInfo("leaving critical section");
LeaveCriticalSection(&gCS);
LogInfo("left critical section");
}
}
At startup, the following print instructions are executed (each print statement prints the number returned with a GetCurrentThreadId()
pre-statement. It looks like the critical section has no effect. For example, thread 7608 acquires the lock and then the next two threads also acquire the lock until it completes. Can anyone- Anyone explain how this can happen?
16004 Critical section initialised
7608 getting lock for critical Section
7608 Entered Critical Section
11412 getting lock for critical Section
11412 Entered Critical Section
12860 getting lock for critical Section
6552 getting lock for critical Section
6552 Entered Critical Section
5524 getting lock for critical Section
5524 Entered Critical Section
7608 leaving critical section
7608 left critical section
thank
+3
source to share
1 answer
According to the documentation :
The throat object cannot be moved or copied.
You are copying a critical section and working on the copy.
Locker(CRITICAL_SECTION& cs): m_cs(cs)
^^^^^^^^
...
CRITICAL_SECTION m_cs;
You presumably wanted to copy the link and not the actual critical section.
CRITICAL_SECTION& m_cs; ^ reference
+6
source to share