Multithreaded Programming Example 2 (combined instance)

Source: Internet
Author: User
Tags mutex semaphore

5. Mutex (mutex)

#pragmaOnce#define_crtdbg_map_alloc#include<cstdio>#include<Windows.h>#include<crtdbg.h>#include<process.h>unsignedintCount =0;ConstUnsignedintThreadnum = -; HANDLE Mutex; critical_section threadpar;unsignedint_stdcall Threadfun (lpvoid pM) {UINT num= * (uint*) PM; ReleaseMutex (Mutex); //Trigger Mutex AmountSleep ( -);//do something.EnterCriticalSection (&Threadpar); ++count; printf ("thread number is%3d, global resource value is%3d\n", NUM, count); LeaveCriticalSection (&Threadpar); return 0;}intMain () {Mutex=CreateMutex (NULL, FALSE, NULL); InitializeCriticalSection (&Threadpar); UINT I=0;    HANDLE Handle[threadnum];  for(i =0; i < threadnum; i++)    {        //Enter the child thread ID number key areaHandle[i] = (handle) _beginthreadex (NULL,0, Threadfun, &i,0, NULL); WaitForSingleObject (Mutex, INFINITE); //wait for mutex to be triggered} waitformultipleobjects (Threadnum, handle, TRUE, INFINITE);    CloseHandle (Mutex); DeleteCriticalSection (&Threadpar);  for(i =0; i < threadnum; i++) {CloseHandle (handle[i]); }    //Detecting Memory leaks_CrtDumpMemoryLeaks (); return 0;}

Operation Result:

Synchronization is still not possible, and the reason is similar to the critical area, where a thread ownership exists.

The interesting thing about mutexes is that it can be used in multi-threaded control between processes, where there is an abandonment process.

For specific reference: http://blog.csdn.net/morewindows/article/details/7470936, very good explanation

6. Semaphore (Semaphore)

#pragmaOnce#define_crtdbg_map_alloc#include<cstdio>#include<Windows.h>#include<crtdbg.h>#include<process.h>unsignedintCount =0;Const intThreadnum = -; HANDLE Threadsemaphore; critical_section threadpar;unsignedint_stdcall Threadfun (lpvoid pM) {UINT num= * (uint*) PM; /*releasesemaphore function Parameter 1: Handle of Semaphore 2: Increment number, must be greater than 0 and not greater than the maximum number of resources 3: Previous resource count, set to NULL indicates no delivery*/ReleaseSemaphore (Threadsemaphore,1, NULL);//Signal Volume + +Sleep ( -);//do something.EnterCriticalSection (&Threadpar); ++count; printf ("thread number is%3d, global resource value is%3d\n", NUM, count); LeaveCriticalSection (&Threadpar); return 0;}intMain () {//initializing semaphores and critical segments    /*createsemaphore Function Description 1: Security Control 2: Initial resource Quantity 3: Maximum concurrent Quantity 4: Name of the semaphore*/Threadsemaphore= CreateSemaphore (NULL,0,1, NULL);//currently 0 resources, up to one simultaneous accessInitializeCriticalSection (&Threadpar); inti =0;    HANDLE Handle[threadnum];  for(i =0; i < threadnum; i++) {Handle[i]= (HANDLE) _beginthreadex (NULL,0, Threadfun, &i,0, NULL); WaitForSingleObject (Threadsemaphore, INFINITE); //wait for Semaphore >0} waitformultipleobjects (Threadnum, handle, TRUE, INFINITE); //destroying semaphores and critical segmentsCloseHandle (Threadsemaphore); DeleteCriticalSection (&Threadpar);  for(i =0; i < threadnum; i++) {CloseHandle (handle[i]); }    //Detecting Memory leaks_CrtDumpMemoryLeaks (); return 0;}

Operation Result:

The semaphore is the same as event, which solves the thread synchronization problem.

Since the semaphore can calculate the current amount of the resource and determine whether the semaphore is in the trigger state or not triggered based on the current remaining amount compared with 0, the signal volume is widely used.

Signal-assisted understanding explanation:

Take the operation of a car park as an example. For simplicity, suppose that there are only three parking spaces in the car park and three spaces are empty at the beginning. At the same time, if five vehicles were to come, the janitor would allow three of them to enter directly, then put down the car block, the rest of the car must wait at the entrance, and then the car will have to wait at the entrance. At this time, there is a car left the parking lot, the janitor learned, open the car block, put into the outside of a car, if left two, then can put two, so reciprocating.
In this parking system, parking spaces are public resources, and each car is like a thread, and the gatekeeper acts as the semaphore.
In abstract terms, the semaphore is characterized as follows: The semaphore is a nonnegative integer (number of spaces), and all threads/processes (vehicles) passing through it will subtract that integer by one (through it, of course, in order to use the resource), and when the integer value is zero, all threads attempting to pass through it will be in the waiting state. On the semaphore we define two actions: Wait (wait) and release (release). When a thread calls the wait operation, it either gets the resource and then cuts the semaphore by one, or waits until it is placed in the blocking queue until the semaphore is greater than or equal to a momentary amount. Release is actually an add operation on the semaphore, which corresponds to the vehicle leaving the parking lot, which is called "release" because of the release of resources guarded by semaphores.

A summary of the amount of mutex semaphore for a critical segment event:

http://blog.csdn.net/morewindows/article/details/7538247 a reference to;

Very classic explanation, multithreaded programming 1, 2 for reference to the contents of the experiment.

Multithreaded Programming Example 2 (combined instance)

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.