Windows core programming-key section (critical section) thread synchronization

Source: Internet
Author: User
Windows core programming-key section (critical section) thread synchronization

Thread Synchronization Methods include critical section, mutex, event, and semaphore.

Next I will focus on how to use the thread synchronization method in critical section in Windows core programming.

Critical section thread synchronization is called key section thread synchronization in Windows core programming.
The key segment is a short piece of code, which requires exclusive access to some resources before execution.
Disadvantage: it can be used only for multi-thread synchronization in one process. A deadlock may occur because we cannot set the maximum wait time for the thread entering the key segment.

Next I will introduce the use of some key segment Thread Synchronization
First look at a case code

int g_nSum = 0;CRITICAL_SECTION g_cs;DWORD WINAPI FirstThread(PVOID pvParam){  EnterCriticalSection(&g_cs);  g_nSum = 0;  for (int n = 0; n < 10000; ++n)  {    g_nSum += n;  }  LeaveCriticalSection(&g_cs);  return g_nSum;}DWORD WINAPI SecondThread(PVOID pvParam){  EnterCriticalSection(&g_cs);  g_nSum = 0;  for (int n = 0; n < 10000; ++n)  {    g_nSum += n;  }  LeaveCriticalSection(&g_cs);  return g_nSum;}

When using the critical_section, there are only two necessary conditions:
1. The thread accessing the resource must know the address of the critical_section object used to protect the resource.
The critical_section object can be allocated as a global object or as a local object,
Or dynamically allocate data from the heap.
2. Before a thread attempts to access protected resources, it must
Members.

Introduction to common functions for Thread Synchronization in key segments

// 1. First, we need to allocate a critical_section object and initialize it (the thread that uses the key segment synchronization must call this function) void initializecriticalsection (lpcritical_section lpcriticalsection) // 2. When the thread no longer needs to access shared resources, we should call the following function to clear the void deletecriticalsection structure of the critical_section (lpcritical_section lpcriticalsection) // 3. Before Accessing Protected Resources, you must call the following void entercriticalsection (lpcritical_section lpcriticalsection). // you can call the preceding function multiple times, indicates the number of times that the call thread is allowed to access. // 4. You can also use the following function to replace entercriticalsectionbool tryentercriticalsection (lpcritical_section lpcriticalsection) // determine whether the current thread is allowed to access resources through the returned, the thread will never enter the waiting state. If // returns true, it indicates that the thread is authorized to access resources and must call leavecriticalsection () when leaving () // 5. After the code completes the access to the resource, you must call the following function to release the access permission void leavecriticalsection (lpcritical_section lpcriticalsection) // repost the article from: http://blog.csdn.net/windows_nt

The preceding access method (entercriticalsection) may change the call thread to the waiting state, which means that the thread must switch from user mode to kernel mode. This overhead is very high. To improve the performance of the key segment, Microsoft merges the rotation lock into the key segment. Therefore, when you call entercriticalsection, it uses a rotation lock to continuously loop and tries to obtain access to the resource within a period of time. Only when the attempt fails, the thread switches to the kernel mode and enters the waiting state.

// 1. In order to use the rotation lock when using the key segment, we must call the following function to initialize the bool initializecriticalsectionandspincount (maid) // The second parameter dwspincount indicates the number of times we want to rotate the lock loop. // 2. You can also call the following function to change the rotation times of key segments. DWORD setcriticalsectionspincount (lpcritical_section lpcriticalsection, DWORD dwspincount) // if the host has only one processor, the function ignores the dwspincount parameter.

The slim read/write lock srwlock allows us to distinguish the threads (the reader thread) that want to read the resource value from the threads (The writer thread) that want to update the resource value ).
// 1. First, we need to allocate an srwlock object and use the following function to initialize it. Void initializesrwlock (_ out psrwlock srwlock) // 2. Requests for exclusive access to protected resources (write permission) void acquiresrwlockexclusive (_ inout psrwlock srwlock) // 3. After the resource is updated, the void releasesrwlockexclusive (_ inout psrwlock srwlock) should be lifted) // 4. The corresponding reader thread function is void acquiresrwlockshared (_ inout psrwlock srwlock) void releasesrwlockshared (_ inout psrwlock srwlock)

Compared with key segments, psrwlock lacks the following two features:
1. There is no function such as tryenter (share/exclusive) srwlock. If the lock is occupied, the call will block the call thread.
2. psrwlock cannot be obtained recursively. That is to say, a thread cannot lock resources multiple times to write resources for multiple times. For example, it can be released multiple times to lock resources.
Sort thread synchronization performance (from high to low)
Read volatile --> write volatile --> interlocked API (atomic mode) --> srwlock --> key segment --> kernel object
Introduction to mutex ----- windows core programming-mutexes)

Related Article

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.