开发者

What does CCriticalSection do?

开发者 https://www.devze.com 2023-02-09 11:33 出处:网络
What the diffrence between this code: ::EnterCriticalSection( &m_CriticalSection ); //... ::LeaveCriticalSection( &m_CriticalSection );

What the diffrence between this code:

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

and the code:

static CCriticalSection cs;
cs.Lock();
//...
cs.UnLock();开发者_运维百科


No difference practically. CCriticalSection is the only syntatic sugar of the former. It internally uses EnterCriticalSection and LeaveCriticalSection!

EnterCriticalSection and LeaveCriticalSection are low-level win32 APIs, while CCriticalSection is a MFC class which wraps these functionalities. It has a member data of type CRITICAL_SECTION which is used by the APIs.

MSDN says,

The functionality of the CCriticalSection class is provided by an actual Win32 CRITICAL_SECTION object.


If you use it that way, there is no difference. The main benefit to the class is if you use it as follows:

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

When the scope is exited the critical section will be unlocked, even if an exception was thrown or an early return was used. The technique is known as RAII (Resource Acquisition Is Initialization) and is widely known.

The MFC synchronisation classes are not that well designed. I would recommend using the boost.thread ones or the ones that will be available in the new C++ standard if you can get your hands on them.


It encapsulates CRITICAL_SECTION structure and the four operations - InitializeCriticalSection(), EnterCriticalSection(), LeaveCriticalSection() and DeleteCriticalSection() into a single class making it more convenient to write code.

0

精彩评论

暂无评论...
验证码 换一张
取 消