Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EnterCriticalSection doesnt seem to be blocking

Tags:

c++

windows

I have the following code to create threads to do some work (with parts ommitted 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");
        }
 }

When it's run, the following print statements occur (each print statement prints the number returned from GetCurrentThreadId() before the statement. It appears as though the critical section is having no effect. Eg. Thread 7608 gets the lock then the two following threads also get the lock before it finishes. Can anyone provide insight into how this might be happening?

 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

Thanks

like image 246
probably at the beach Avatar asked Mar 18 '23 04:03

probably at the beach


1 Answers

According to the documentation:

A critical section object cannot be moved or copied.

You are copying the critical section and operating on the copy.

Locker(CRITICAL_SECTION& cs): m_cs(cs)
                              ^^^^^^^^
...
CRITICAL_SECTION m_cs;

You presumably wanted to copy the reference, not the actual critical section.

CRITICAL_SECTION& m_cs;
                ^ reference
like image 178
Raymond Chen Avatar answered Apr 08 '23 05:04

Raymond Chen