"Multithreading" Learning 14

Source: Internet
Author: User
Tags semaphore volatile

Make a small summary:

What is the key segment, the mutex, the event, and the semaphore, if we are to compare things in real life?

The sense event is like a pause continuation key,
WaitForSingleObject is paused
SetEvent is the continuation can be repeated multiple press continue but if there is no pause in the middle of no meaning
The purpose of the continuation is to wait for the condition to be satisfied, so the meaning of the event is to find the waiting relationship between threads.

It doesn't make sense to use SetEvent and WaitForSingleObject for the same event in the same thread.
What's resetevent?

The following analogy does not come out .....


The waitforsingleobject-->releasemute of the mutex, the entercriticalsection-->leavecriticalsection of the critical section, must be executed within the same thread, Thread A has ownership of the resource, then the release of all rights must also be performed by thread A

The purpose of mutexes and critical segments seems to be, in addition to the differences between the user object kernel objects, whether the difference between the threading and abandonment is fundamentally different?

See: Http://www.cnblogs.com/huhuuu/p/3589590.html contains an example of the difference between a mutex and a key segment in the same process, using the same effect:

The individual uses the more common generator consumer model slightly to make the variant, has become 4 producers, 4 consumers, 4 critical area resources:

Using the semaphore Full,empty to represent the resource of the critical section, the key segment is used to treat the mutually exclusive access to the variable.

#include <stdio.h>#include<process.h>#include<windows.h>volatile  LongG_nlogincount;Const intThread_num =Ten;volatile  LongG_num; HANDLE G_mutex; HANDLE G_semaphore_full,g_semaphore_empty; //Signal Volumecritical_section G_thread;intnum=Ten; unsignedint__stdcall Producer (void*PPM) {    inti;  for(i=0;i<4; i++) {Sleep ( -);        WaitForSingleObject (G_semaphore_empty,infinite); Sleep ( -);
       printf ("producer id:%d\n", GetCurrentThreadID ());    
//entercriticalsection (&g_thread);//There's no problem with the critical section.WaitForSingleObject (g_mutex,infinite);//There's going to be a problem with mutexes .g_num++; printf ("producer id:%d Cumulative sum:%d\n", GetCurrentThreadID (), g_num); ReleaseMutex (&G_mutex); //leavecriticalsection (&g_thread);ReleaseSemaphore (G_semaphore_full,1, NULL);//Signal Volume + +Sleep (Ten); }    return 0;} unsignedint__stdcall Customer (void*PPM) {    intok=1;  while(1){        //Sleep (0);Sleep ( -); Sleep (0);        WaitForSingleObject (G_semaphore_full,infinite); printf ("consumer id:%d Cumulative sum:%d\n", GetCurrentThreadID (), g_num); ReleaseSemaphore (G_semaphore_empty,1, NULL);//Signal Volume + +    }    return 0;}intMain () {G_semaphore_full= CreateSemaphore (NULL,0,4, NULL);//currently 0 resources, maximum allowed 4 simultaneous visitsG_semaphore_empty = CreateSemaphore (NULL,0,4, NULL);//currently 0 resources, maximum allowed 4 simultaneous visitsG_mutex =CreateMutex (null,false,null); InitializeCriticalSection (&g_thread); HANDLE handle[Ten]; ReleaseSemaphore (G_semaphore_empty,4, NULL);//Signal Volume + +    inti;  for(i=0;i<4; i++) {Handle[i]= (HANDLE) _beginthreadex (NULL,0, Producer,null,0, NULL); }     for(i=0;i<4; i++) {Handle[i+4] = (HANDLE) _beginthreadex (NULL,0, Customer,null,0, NULL);    } waitformultipleobjects (Thread_num,handle,true,infinite); GetChar (); //Be sure to set it up here so that the main thread stops, otherwise the child thread is shut down if it executes to the back     for(i=0;i<6; i++) CloseHandle (Handle[i]);    CloseHandle (G_semaphore_full);    CloseHandle (G_semaphore_empty);    CloseHandle (G_mutex); return 0;}

See the effect of the key section of the left image with the mutex effect shown on the right

The use of mutex output is completely orderly, this should not AH. According to the output, start 4 production line successively want to lock, a thread wins, but after the line threads unlocked, theoretically should other

Three already waiting line loads lock, but actually still this already has the mutex the thread wins??

Have to think that because the mutex has ownership, in a number of waiting for the first choice, but tried the following code, but there is no problem.

#include <Windows.h>#include<process.h>#include<stdio.h>intTickets = -; HANDLE Hmutex;dword WINAPI thread1fun (lpvoid lpparam) { while(1) {WaitForSingleObject (Hmutex, INFINITE); if(Tickets >0) {printf ("ID =%d T1 =%d\n", GetCurrentThreadID (), tickets--); }        Else        {             Break;        } ReleaseMutex (Hmutex); Sleep ( -); }    return 0;} DWORD WINAPI Thread2fun (lpvoid lpparam) { while(true) {WaitForSingleObject (hmutex,infinite); if(tickets>0) {printf ("ID =%d t2 =%d\n", GetCurrentThreadID (), tickets--); }          Else          {               Break;        } ReleaseMutex (Hmutex); Sleep ( -); }        return 0; } intMain () {HANDLE hThread1, hThread2, HThread3, hThread4; HThread1= CreateThread (NULL,0, Thread1fun, NULL,0, NULL); HThread2= CreateThread (NULL,0, Thread2fun, NULL,0, NULL); HThread3= CreateThread (NULL,0, Thread1fun, NULL,0, NULL); HThread4= CreateThread (NULL,0, Thread2fun, NULL,0, NULL);      CloseHandle (HTHREAD1);     CloseHandle (HTHREAD2);      CloseHandle (HTHREAD3);     CloseHandle (HTHREAD4); Hmutex=CreateMutex (NULL, FALSE, NULL); //true means that the main thread owns the mutex object but the main thread does not release the object mutex who owns who releases//flase means that no thread currently owns this mutex objectSleep (40000); return 0;}

Also is a thread inside the mutex used many times, why the result of this code is unordered?


Thread ownership: Key segment, mutex

Differentiation of processing conditions:

Event: For example, the water is boiling to make the noodles.
The following bar _ thread

WaitFor (water boil) the following bar


Boiling water Thread

Boiling water Set (boil)

The process of dealing with the relationship of time, if in a thread is sequential execution, multiple threads inside the need to synchronize.

Signal Volume: Canteen When the meal, there is a dish of the area, as long as there are dishes in the area can be taken, as long as there is open space in the area can be put vegetables.
If you are full, you can not put vegetables, if empty customers will not be able to take the dishes. The semaphore has a concept of capacity.

"Multithreading" Learning 14

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.