What does CCriticalSection do?

What is the difference between this code:

::EnterCriticalSection( &m_CriticalSection ); //... ::LeaveCriticalSection( &m_CriticalSection ); 

and code:

 static CCriticalSection cs; cs.Lock(); //... cs.UnLock(); 
+4
source share
3 answers

There is practically no difference. CCriticalSection is the first syntactic sugar of the first. It internally uses EnterCriticalSection and LeaveCriticalSection!

EnterCriticalSection and LeaveCriticalSection are low-level win32 APIs, and CCriticalSection is the MFC class that wraps these functions. It has data for an element of type CRITICAL_SECTION , which is used by the API.

MSDN says

Functionality The CCriticalSection class is provided by the actual Win32 CRITICAL_SECTION object.

+8
source

If you use it this way, there is no difference. The main advantage of this class is that you use it as follows:

 static CCriticalSection cs; { CSingleLock lock(cs, true); // do your work here } // unlocked automatically 

At the end of the region, the critical section will be unlocked, even if an exception was thrown or an early return was used. This technology is known as RAII (Initialization of Resources) and is widely known.

The MFC sync classes are not so well designed. I would recommend using boost.thread or those that will be available in the new C ++ standard if you can use it.

+7
source

It encapsulates the CRITICAL_SECTION structure and four operations - InitializeCriticalSection() , EnterCriticalSection() , LeaveCriticalSection() and DeleteCriticalSection() in one class, which makes it more convenient for writing code.

+2
source

Source: https://habr.com/ru/post/1339141/


All Articles