C + + Supplements-Multithreading: critical section resolves mutex for sub-threads
Preface
In order to solve the mutex problem of sub-threads, the Windows system presents the concept of critical segment or critical section (critical_section). It has four total of two operations: Initialize, destroy, enter, leave. They are defined in the header file synchapi.h.
1. Initializing variables
VOID WINAPI InitializeCriticalSection (
Lpcritical_section lpcriticalsection
);
2. Destroying variables
VOID WINAPI DeleteCriticalSection (
Lpcritical_section lpcriticalsection
);
3. Enter the critical area
VOID WINAPI EnterCriticalSection (
Lpcritical_section lpcriticalsection
);
Function Description: The system guarantees that each sub-thread is mutually exclusive into the critical area
4. Leave the critical area
VOID WINAPI LeaveCriticalSection (
Lpcritical_section lpcriticalsection
);
All four functions are fairly simple to use, passing in a variable address of type critical_section.
BodySample Program
Here we use the key segments to solve the mutex problem of the child thread, and the program code is similar to atomic operations to resolve thread conflicts. Each child thread accumulates 10 for the same global variable. This time we turn on 50 sub-threads to see the last cumulative result.
Run
From the running results, it is true that the use of critical segments can resolve the conflict of child threads. Before and after the g_count++, we add the entry and departure of the critical section, making the Code a "critical" area. At this point, g_count++, the operation is very similar to atomic operations. Let's analyze the usage principle of the key section in detail below.
Key Segmentprinciple
Definition of key segment
In the Minwinbase.h
typedef rtl_critical_section CRITICAL_SECTION;
And in the WinNT.h,
typedef struct _RTL_CRITICAL_SECTION {
Prtl_critical_section_debug Debuginfo;
//
The following three fields control entering and exiting the critical
Section for the Resource
//
LONG Lockcount;
LONG Recursioncount;
HANDLE OwningThread; From the thread ' s Clientid->uniquethread
HANDLE LockSemaphore;
ULONG_PTR Spincount; Force size on 64-bit systems when packed
} rtl_critical_section, *prtl_critical_section;
The critical segment is a struct. Specific reasons for follow-up analysis ...
Directory of this column
- C + + Supplements directory
Directory of all content
C + + Supplements-Multithreading: critical section resolves mutex for sub-threads