Windows multithreading (vi) mutex mutex vs. critical segment CriticalSection Comparison

Source: Internet
Author: User

The same point of the key segment CS and mutex mutex: All threads have the right to

Both the critical segment and the mutex are wired to be owned by a thread. In the previous article on critical section CS, it is said that the fourth parameter of the key segment structure holds the handle to the thread that owns the key segment, as follows:

typedef   _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;  
    • First parameter: Prtl_critical_section_debug debuginfo; When debugging, do not introduce the first.

    • Second parameter: LONG lockcount; Initializing to -1,n indicates that there are N threads waiting.

    • A third parameter: LONG recursioncount; Indicates that the owning thread for this critical segment has a critical number of times for this resource, beginning with 0.

    • Fourth parameter: HANDLE owningthread; That is, the thread handle that owns the critical segment

    • Fifth parameter: HANDLE LockSemaphore; is actually a self-resetting event.

    • Sixth parameter: Ulong_ptr Spincount; Rotation lock settings for multi-processor.

Now let's analyze the following programs:

#include <iostream>#include <windows.h>using namespaceStdConst unsigned intThread_num =Ten;unsigned intG_count =0; critical_section Cs;dword WINAPI ThreadFunc (LPVOID);intMain () {initializecriticalsection (&AMP;CS); HANDLE Hthread[thread_num]; for(inti =0; i < Thread_num; i++) {entercriticalsection (&AMP;CS);//Enter the key section, execute this sentence when the main thread gets the ownership of this key segment. Hthread[i] = CreateThread (NULL,0, ThreadFunc,0,0, NULL); } waitformultipleobjects (Thread_num, Hthread,true, INFINITE); cout << Thread_num <<"All Threads return"<< Endl;return 0;} DWORD WINAPI ThreadFunc (LPVOID p) {leavecriticalsection (&AMP;CS);//Leave critical segmentSleep ( -); EnterCriticalSection (&AMP;CS);//Enter key sectioncout<<"The value of G_count is:"<<g_Count++<<endl; LeaveCriticalSection (&AMP;CS);//Leave critical segmentSleep ( -);return 0;}

As shown by adding two breakpoints to debug, normally the program should be followed by two breakpoints, but when debugging we found that the program will repeatedly enter the first breakpoint, this is because the first breakpoint is executed when the main thread to obtain the ownership of this key segment.

Similarly, mutexes have thread ownership and need to know the mutex to see here. As above, we write a program like this

  #include <iostream> #include <windows.h>using namespace std;const unsigned int Thread_num = 10;unsigned int g_count = 0; Critical_section CS;    HANDLE G_mutex;dword WINAPI ThreadFunc (LPVOID); int main () {initializecriticalsection (&CS);  G_mutex = CreateMutex (null, FALSE, NULL);    Initialize the mutex as the trigger state HANDLE Htread[thread_num];  for (int i = 0; i < thread_num;i++) {WaitForSingleObject (G_mutex, INFINITE);          Wait for mutex trigger htread[i] = CreateThread (NULL, 0, threadfunc, 0, 0, NULL);    } waitformultipleobjects (Thread_num, Htread, True, INFINITE);    cout << thread_num << "All Threads return" << Endl; return 0;}    DWORD WINAPI ThreadFunc (LPVOID p) {//releasemutex (G_mutex);    Sleep (50);  EnterCriticalSection (&CS);    Enter key section cout << "G_count value:" << g_count++ << Endl;  LeaveCriticalSection (&CS);    Leave the key section Sleep (50);  ReleaseMutex (G_mutex); Trigger mutex return 0;}  

Similarly, we have two breakpoints in the program, and the program repeats the first breakpoint without passing the second breakpoint.

Previous critical segment and mutex two articles we said the key section CS and mutex mutex can not do thread synchronization, only the critical resource mutually exclusive access, is because, he they are all wired to have the right reason.

Second, the key section CS and mutex mutex different points: because the mutex is often used for the thread mutex between multiple processes, it is more useful than the key section of the feature-"abandonment" situation of processing.

Look at the following program:

Program One:

#include <stdio.h>#include <windows.h>constchar"MyMutex"//互斥量名字int main(){    //创建互斥量并初始化为未触发状态    printf("互斥量已经创建,按任意键触发\n");    getch();    exit(0//在互斥量触发前退出程序。    //ReleaseMutex(hMutex); // 触发互斥量    printf("互斥量已经被触发\n");    CloseHandle(hMutex);    return0;}

Program Two:

#include <stdio.h>#include <windows.h>Const CharMutexname[] ="Mymutex";//Mutex nameintMain () {HANDLE Hmutex = OpenMutex (mutex_all_access, TRUE, mutexname);//Open Mutex amount        if(NULL! = Hmutex) {printf ("Open mutex succeeded, wait for mutex to be triggered\ n"); DWORD mRes = WaitForSingleObject (Hmutex, INFINITE);//wait for mutex to be triggered        if(wait_abandoned = = mRes)//Determine if the mutex is abandoned{printf ("Mutex is abandoned. \ n"); }//printf ("The mutex has been triggered \ n");}Else{printf ("Mutex open failed. \ n"); } closehandle (Hmutex);return 0;}

Run first, program one, and then run program two as shown in.

At this time, in the program one press any key, so that the program one in the mutex does not trigger before exiting, the program two output as follows:

This is an incorrect place to learn while writing, welcome to point out!!!!!

Windows multithreading (vi) mutex mutex vs. critical segment CriticalSection Comparison

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.