"Multithreading" Learning 6

Source: Internet
Author: User

The following are from: http://blog.csdn.net/morewindows/article/details/7470936

The use of critical section CS and event events in the classic thread synchronization problem is described earlier. This article describes the use of mutex mutex to solve this problem.

A mutex is also a kernel object that is used to ensure that a thread is exclusive of access to a resource. Mutexes are very similar to the behavior of critical segments, and mutexes can be used for mutually exclusive access to resources in different processes . Using mutex mutexes will primarily use four functions. Here are the prototypes and instructions for using these functions.

The first of the CreateMutex

function function: Create mutex (note vs. event creation function)

Function Prototypes:

HANDLE CreateMutex (

lpsecurity_attributes lpmutexattributes,

BOOL Binitialowner,

lpctstr lpname

);

Function Description:

The first parameter represents the security control, which is typically passed directly to null.

The second parameter is used to determine the initial owner of a mutex. If passed in true means that the thread ID number of the thread that created it is logged inside the mutex object and the recursive count is set to 1, because the thread ID is nonzero, the mutex is not in the triggered state. If False is passed in, the thread ID number inside the mutex object is set to NULL, and the recursive count is set to 0, which means that the mutex is not occupied by any thread and is in a triggered state.

The third parameter is used to set the name of the mutex, in which threads in multiple processes make sure that they are accessing the same mutex by name.

function Access Value:

Successfully returns a handle representing the mutex, and the failure returns NULL.

Second Open mutex

Function Prototypes:

HANDLE OpenMutex (

DWORD dwdesiredaccess,

BOOL bInheritHandle,

LPCTSTR lpname//Name

);

Function Description:

The first parameter represents access rights, and the mutex is generally passed into mutex_all_access. Detailed explanations can be viewed in the MSDN documentation.

The second parameter represents the mutex handle inheritance, which is generally passed to true.

The third parameter represents a name. After a thread in a process creates a mutex, the thread in the other process can find the mutex through this function.

function Access Value:

Successfully returns a handle representing the mutex, and the failure returns NULL.

Third Trigger Mutex

Function Prototypes:

BOOL ReleaseMutex (HANDLE Hmutex)

Function Description:

You should call the wait function before accessing the mutex, call ReleaseMutex () at the end of the visit to indicate that you have ended the access, and the other threads can begin to access it.

Last cleanup mutex

Because the mutex is a kernel object, it is possible to use CloseHandle() (which is the same for all kernel objects).

Next we will try to use mutual exclusion in the classic multithreading problem to ensure the synchronization between the main thread and the child thread, since the use of the mutex function is similar to event events, so you can follow the implementation of the previous article to write code:

#include <stdio.h>#include<process.h>#include<Windows.h>Longg_nnum;unsignedint__stdcall Fun (void*PPM);Const intThread_num =Ten;//Mutex and key segmentHANDLE G_hthreadparameter; critical_section G_csthreadcode;intMain () {//initialize the mutex with the key segment the second argument is true to indicate that the mutex is all created for the threadG_hthreadparameter =CreateMutex (NULL, FALSE, NULL); InitializeCriticalSection (&G_csthreadcode);    HANDLE Handle[thread_num]; G_nnum=0; inti =0;  while(I <thread_num) {Handle[i]= (HANDLE) _beginthreadex (NULL,0, Fun, &i,0, NULL);        WaitForSingleObject (G_hthreadparameter, INFINITE); I++;        } waitformultipleobjects (Thread_num, handle, TRUE, INFINITE); //destroying mutexes and critical segmentsCloseHandle (G_hthreadparameter); DeleteCriticalSection (&G_csthreadcode);  for(i =0; i < Thread_num; i++) CloseHandle (Handle[i]); return 0; }unsignedint__stdcall Fun (void*PPM) {      intNthreadnum = * (int*) PPM; ReleaseMutex (g_hthreadparameter);//Trigger Mutex AmountSleep ( -);//some work shouldEnterCriticalSection (&G_csthreadcode); G_nnum++; Sleep (0);//some work shouldprintf"Thread number%d global resource value is%d\n", Nthreadnum, g_nnum); LeaveCriticalSection (&G_csthreadcode); return 0; }  

It can be seen that, like the critical segment, mutexes do not resolve synchronization problems between threads .

Lenovo to the key section will record the thread ID is "thread ownership", and the mutex also records the thread ID, it is also a "thread ownership" of the argument.

The answer is true, and the mutex also has the concept of "thread ownership". "Thread ownership" is described in detail in the key section, which is not discussed here. In addition, because mutexes are often used for thread mutexes between multiple processes, it has a more useful feature than critical segments-the handling of " abandonment " situations. For example, if a thread that occupies a mutex terminates unexpectedly before calling ReleaseMutex() to trigger a mutex (equivalent to the mutex being "abandoned"), will all threads waiting for this mutex be caught in an infinite wait process because the mutex cannot be triggered? This is obviously unreasonable. Since the thread that occupies a mutex is terminated, it is sufficient to prove that it is no longer using the resources protected by the mutex, so these resources are fully and should be used by other threads. Therefore, in this " abandonment " case, the system automatically sets the internal thread ID of the mutex to 0, and its recursive counter is reset to 0, indicating that the mutex is triggered. Then the system will "fairly" select a waiting thread to complete the dispatch ( WaitForSingleObject() of the selected thread will return wait_abandoned_0).

The following two programs are written to verify the following:

The first program creates a mutex and waits for the user to enter it to trigger the mutex. The second program opens the mutex, waits for success and then outputs the corresponding output according to the waiting result. See the code:

First Program:

#include <stdio.h>#include<conio.h>#include<windows.h>Const CharMutex_name[] ="Mutex";intMain () {HANDLE Hmutex= CreateMutex (NULL, TRUE, mutex_name);//Create Mutex Amountprintf"mutex has been created, now press any key to trigger the mutex \ n");    Getch (); //exit ( 0);    ReleaseMutex (Hmutex); printf ("The mutex has been triggered and can be called by another thread \ n");    CloseHandle (Hmutex); return 0;}

Second program:

#include <stdio.h>#include<windows.h>Const CharMutex_name[] ="Mutex";intMain () {HANDLE Hmutex= OpenMutex (mutex_all_access, TRUE, mutex_name);//Open Mutex Amount    if(Hmutex = =NULL) {printf ("failed to open mutex \ n"); return 0; } printf ("waiting .... \ n"); DWORD Dwresult= WaitForSingleObject (Hmutex, -* +);//wait for mutex to be triggered    Switch(dwresult) { Casewait_abandoned:printf ("the process with the mutex terminated unexpectedly \ n");  Break;  Casewait_object_0:printf ("I 've received a signal \ n");  Break;  Casewait_timeout:printf ("The signal is not delivered to \ n within the specified time.");  Break;      } closehandle (Hmutex); return 0; }

Use these two programs to start the program repeatedly start the program two. Some of the output results are shown below:

Result one. Two processes completed successfully:

Result two. The program One//exit (0), the preceding comment symbol is removed, so that the program one before triggering the mutex will be executed exit (0), the statement and exit, program two will receive the wait_abandoned message and output "The mutex process terminated unexpectedly":

With this handling of " abandonment " issues, thread synchronization in multiple processes can also be assured of the use of mutexes.

Finally, the following mutex mutexis summarized:

1. A mutex is a kernel object that has "thread ownership" of a critical segment and cannot be used for thread synchronization.

2. Mutexes can be used for thread mutex issues between multiple processes, and can perfectly solve the "abandonment" problem caused by an unexpected termination of a process.

"Multithreading" Learning 6

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.