Use of CCriticalSection

Source: Internet
Author: User

The CCriticalSection is the encapsulation of the key section CRITICAL_SECTION.
 
Critival section is a short piece of code that requires exclusive access to some shared resources before execution. This method allows multiple lines of code to manipulate resources in an atomic manner. Here, the "Atomic mode" means that the code knows that no thread except the current thread will access this resource at the same time. Of course, the system can still pause the current thread to schedule other threads. However, before the current thread leaves the key segment, the system will not schedule any other threads that want to access the same resource.
For example, if two threads access a linked list at the same time, one thread may search for an element in the linked list and add an element to the linked list, which leads to incorrect search results; it is also possible that two threads add elements to the linked list at the same time, which will become more chaotic. Even when one thread searches, another thread deletes the linked list node, which will directly cause the program to crash.
To solve this problem, we can define a CRITICAL_SECTION Data Structure m_sect in the code, and then place any code that requires access to shared resources between EnterCriticalSection and LeaveCriticalSection.
 
[Cpp]
EnterCriticalSection (& m_sect );
// Code segment of the shared resource ....
 
LeaveCriticalSection (& m_sect );

A CRITICAL_SECTION structure is like a bathroom on an airplane, while a restroom is the resource we want to protect (the restroom is surrounded by a wall consisting of EnterCriticalSection and LeaveCriticalSection "). Because the bathroom is small, only one person is allowed to use the restroom in the bathroom at the same time (only one thread is allowed to use protected resources in the key segment at the same time ).
If there are multiple resources that should always be used together, we can put them in the same "bathroom": we only need to create a CRITICAL_SECTION structure to protect all these resources.
 
Master the following key sections:
1. Any code to access Shared resources must be included between EnterCriticalSection and LeaveCriticalSection. If you forget a place, shared resources may be damaged. Forgetting to call EnterCriticalSection and LeaveCriticalSection is like forcibly entering the bathroom without permission. The thread forcibly enters and controls the resource. As long as a thread has such a crude behavior, the resources will be destroyed.
2. The key section CRITICAL_SECTION is an undisclosed structure, because Microsoft believes that developers do not need to understand the details of this structure. For us, we do not need to know the member variables in this structure. We should never use their members when writing code.
3. to manipulate the CRITICAL_SECTION structure, we must call the Windows API function to input the structure address. (Note the address !) That is to say, if the lifecycle of the CRITICAL_SECTION structure is not over, you can pass the structure address to any thread in any way you like.
4. Before any thread attempts to access protected resources, it must initialize the internal Member processes of the CRITICAL_SECTION structure. We do not know the internal members, but we can call the Windows function implementation: void winapi InitializeCriticalSection (_ out LPCRITICAL_SECTION lpCriticalSection );
5. When the thread no longer needs to access shared resources, call the following function to clear the structure: void winapi DeleteCriticalSection (_ inout LPCRITICAL_SECTION lpCriticalSection );
 
6. In fact, CRITICAL_SECTION does not know what resources are shared, nor does it intelligently protect shared resources. Basically, if multiple threads call the EnterCriticalSection at the same time, only one thread will return the result, and the other threads will suspend the execution and wait until the previous thread calls the LeaveCriticalSection before executing the execution.
 
7. It can be seen that there is no timeout setting for entering the key segment, as if it would never have timed out. In fact, calls to EnterCriticalSection will also time out and cause exceptions. The timeout duration is determined by the CriticalSectionTimeout value in the following registry subitem:
HKEY_LOCAL_MACHINE \ System \ CurrentControlSet \ Control \ Session Manager
The value is in seconds. The default value is 2592000 seconds, which is about 30 days.
 
8. The same thread can enter a key segment for N times. That is to say, the same thread will return any number of calls to EnterCriticalSection. Whether different threads can enter the key section depends on whether there are threads in the EnterCriticalSection parameter (the address of the CRITICAL_SECTION structure. Remember: there are multiple toilets on the plane. You can enter unattended toilets without entering others' ones.
 
 
After understanding CRITICAL_SECTION, It is very convenient to use the CCriticalSection. Check the Code:
// Header file
[Cpp]
Class CCriticalSection: public CSyncObjet
{...
Public:
CRITICAL_SECTION m_sect;
Public:
BOOL Unlock ();
BOOL Lock ();
BOOL Lock (DWORD dwTimeout );
...
}
[Cpp]
<P> // constructor </p> CCriticalSection: CCriticalSection (): CSyncObject (NULL)
{
HRESULT hr = S_ OK;
If (! InitializeCriticalSectionAndSpinCount (& m_sect, 0) // it can be understood as InitializeCriticalSection. A rotation lock is added for efficiency.
{
Hr = HRESULT_FROM_WIN32 (GetLastError ());
}

If (FAILED (hr ))
{
AtlThrow (hr );
}
}
 
// Enter the key segment
[Cpp]
BOOL CCriticalSection: Lock ()
{
: EnterCriticalSection (& m_sect );
 
Return TRUE;
}


// Exit the key segment
[Cpp]
BOOL CCriticalSection: Unlock ()
{
: LeaveCriticalSection (& m_sect );

Return TRUE;
}

// Structure
[Cpp]
CCriticalSection ::~ CCriticalSection ()
{
: DeleteCriticalSection (& m_sect );
}

 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.