Thread critical section related structures and functions

Source: Internet
Author: User
Tags stack trace

    单进程的线程可以使用临界资源对象来解决同步互斥问题,该对象不能保证哪个线程能够获得到临界资源对象,因而该系统能公平的对待每一个线程。    每个进程中访问临界资源的那段代码称为临界区(Critical Section)(临界资源是一次仅允许一个进程使用的共享资源)。每次只准许一个进程进入临界区,进入后不允许其他进程进入。不论是硬件临界资源,还是软件临界资源,多个进程必须互斥地对它进行访问。

The critical section of a multiple process involving the same critical resource is called the relevant critical region.
The scheduling principle of a process entering a critical section is:
1. If there are several processes that require access to an idle critical section, only one process is allowed to enter at a time.
2. At any time, there must be more than one process in the critical area. If a process has entered its own critical section, all other processes attempting to enter the critical section must wait.
3, the process of entering the critical area should be exited within a limited time so that other processes can enter their critical areas in time.
4, if the process can not enter their own critical section, you should give up the CPU, to avoid the process of "busy" phenomenon.
When multiple threads attempt to access the critical section at the same time, all other threads that attempt to access this critical section after a thread has entered will be suspended and continue until the thread that enters the critical section leaves. When the critical section is released, other threads can continue to preempt, and in this way achieve the purpose of atomic manipulation of shared resources.
The critical section uses the CRITICAL_SECTION structure object to protect shared resources when used, and uses the EnterCriticalSection () and leavecriticalsection () functions respectively to identify and release a critical section. The CRITICAL_SECTION structure object used must be initialized by InitializeCriticalSection () before it can be used, and you must ensure that any code in any thread that attempts to access this shared resource is protected by this critical section. Otherwise the critical section will not play its rightful role, and the shared resources may still be compromised.

The view code in WinBase.h can see the following definition:

typedef RTL_CRITICAL_SECTION CRITICAL_SECTION;

You can see the definition of struct rtl_critical_section in WinNT.h:

typedefstruct _RTL_CRITICAL_SECTION {PRTL_CRITICAL_SECTION_DEBUG DebugInfo;LONG LockCount;LONG RecursionCount;HANDLE OwningThread;HANDLE LockSemaphore;ULONG_PTR SpinCount;} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;

Each field is described in the following paragraphs:
Debuginfo This field contains a pointer to the adjoint structure of the system assignment, which is of type Rtl_critical_section_debug. This structure contains more valuable information, also defined in WINNT. H.

Lockcount This is the most important field in the critical section. It is initialized to a value of 1; This value is equal to or greater than 0 o'clock, indicating that this critical section is occupied. When it is not equal to-1, the OwningThread field (this field is incorrectly defined in WINNT. H-should be a DWORD instead of HANDLE) contains the thread ID that owns this critical section. The difference between this field and the (RecursionCount-1) value indicates how many other threads are waiting to obtain the critical section.

Recursioncount
This field contains the number of times that the owner thread has obtained the critical section. If the value is zero, the next thread attempting to acquire the critical section succeeds.

OwningThread This field contains the thread identifier of the thread that is currently occupying this critical section. This thread ID is the same as the ID returned by an API such as GetCurrentThreadID.

LockSemaphore
This field is not named properly, it is actually a self-resetting event, not a signal. It is a kernel object handle that notifies the operating system that the critical section is now idle. The operating system automatically creates such a handle when a thread first attempts to obtain the critical section, but is blocked by another thread that already owns the critical section. The deletecriticalsection should be called (it will emit a closehandle call to invoke the event and, if necessary, release the debug structure), otherwise a resource leak will occur.

Spincount
For multi-processor systems only. The MSDN documentation describes this field as follows: "In a multiprocessor system, if the critical section is unavailable, the calling thread rotates dwspincount times before performing a wait operation on the signal associated with that critical section. If the critical section becomes available during the rotation operation, the calling thread avoids the wait operation. The rotation count can provide better performance on multiprocessor computers because rotating in a loop is usually faster than entering kernel-mode wait states.

The RTL_CRITICAL_SECTION_DEBUG structure is mentioned in the first parameter, which is briefly described below:

typedefstruct _RTL_CRITICAL_SECTION_DEBUG {WORD Type;WORD CreatorBackTraceIndex;struct _RTL_CRITICAL_SECTION *CriticalSection;LIST_ENTRY ProcessLocksList;DWORD EntryCount;DWORD ContentionCount;DWORD Flags;WORD CreatorBackTraceIndexHigh;WORD SpareWORD ;} RTL_CRITICAL_SECTION_DEBUG, *PRTL_CRITICAL_SECTION_DEBUG, RTL_RESOURCE_DEBUG, *PRTL_RESOURCE_DEBUG;

Parameter description:
Type This field is not used and is initialized to a numeric value of 0.

Creatorbacktraceindex This field is used only in diagnostic scenarios. Under registry key HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File execution Options\yourprogram is Keyfield, GlobalFlag and STACKTRACEDATABASESIZEINMB values. Note that these values are displayed only when you run the Gflags command that is described later. When these registry values are set correctly, the Creatorbacktraceindex field is populated with an index value that is used in the stack trace.

CriticalSection points to the rtl_critical_section associated with this structure.
Processlockslist List_entry is a standard Windows data structure used to represent nodes in a doubly linked list. The rtl_critical_section_debug contains a portion of the linked list, allowing the critical section to be traversed forward and backward. The utilities shown later in this article show how to use Flink (forward link) and Blink (back link) fields to move between members in a linked list. Anyone who has worked on a device driver or studied the Windows kernel will be familiar with this data structure.
Entrycount/contentioncount These fields are incremented at the same time, for the same reason. This is the number of threads that enter the wait state because they cannot get the critical section immediately. Unlike the Lockcount and Recursioncount fields, these fields are never decremented.

Spares these two fields are not used or even initialized (although these fields are cleared 0 when the critical section structure is deleted). It will be explained later that you can use these unused fields to save useful diagnostic values.

VOID initializecriticalsection (lpcritical_section lpcriticalsection)
The function function initializes a critical resource object.
The function has no return value. Each thread of a single process can use a critical resource object to resolve a synchronization mutex problem, which does not guarantee which thread is able to obtain a critical resource object, and that the system can treat every thread fairly.

 多个线程操作相同的数据时,一般是需要按顺序访问的,否则会引导数据错乱,无法控制数据,变成随机变量。为解决这个问题,就需要引入互斥变量,让每个线程都按顺序地访问变量。这样就需要使用EnterCriticalSection和LeaveCriticalSection函数。
VOID// critical section);VOID// critical section);//删除关键节对象释放由该对象使用的所有系统资源。VOID// critical section);

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Thread critical section related structures and functions

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.