Seconds to kill multithreading 15th key segment, event, mutex, semaphore "abandonment" problem

Source: Internet
Author: User
Tags semaphore terminates

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Directory (?) [+]

Seconds to kill multithreading 15th key segment, event, mutex, semaphore "abandonment" problem

In the second-kill multi-threaded Nineth Classic thread synchronization summary of the key segments of the event mutex signal volume of the classic multi-threaded synchronization mutual exclusion of the problem is reviewed and summarized, this article on the Windows system commonly used thread synchronization mutex-key segment, event, mutex, signal volume is summarized. Some netizens ask the mutex can deal with "abandonment" problem, whether the event and Semaphore can also deal with "abandonment" problem. So this article will be a test of events and semaphores to see if events and semaphores can deal with the problem of "abandonment".

I. What is the "abandonment" problem

In the second multi-threaded seventh classic thread synchronization mutex mutex, the mutex can deal with the problem of "abandonment", the following text is quoted:

Mutexes are often used for thread mutexes between multiple processes, so 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 problem with "abandonment" can be seen--whether the process of owning a resource terminates unexpectedly and the other processes waiting for that resource are aware.

Two "Abandonment" Issues in key sections

Critical segments are simple on this issue-because critical segments cannot be used across processes, critical segments do not need to deal with "abandonment" issues.

Three event, mutex, semaphore "abandonment" problem

Events, mutexes, semaphores are kernel objects that can be used across processes. After a process creates a named event, other processes can call OpenEvent () and pass in the name of the event to get a handle to the event. So events, mutexes, and semaphores all encounter "abandonment" issues. We already know that mutexes can handle "abandonment", and then we'll look at whether events and semaphores can handle "abandonment" issues. Similar to the second-kill multi-threaded seventh classic thread synchronization mutex mutex of the experiment done on the mutex, the following also on the event and the semaphore as the same experiment:

1. Create two processes.

2. Process one creates an event that is initially not triggered and then waits for the key, pressing Y to end the process after the event is triggered, or a direct exit to indicate that the process has terminated unexpectedly.

3. The process two obtains the handle of the event first, then calls WaitForSingleObject () to wait for this event for 10 seconds, in which case the output "received signal" if the event has already been triggered, otherwise the output "does not receive a signal within the specified time". If the process terminates unexpectedly during the wait, the output "the process that owns the event terminates unexpectedly". The signal volume is tested in a similar way.

To enhance the contrast, the test results of the mutex are shown first (see the second-kill multithreading seventh classic thread synchronization mutex mutex)

It can be seen that the second process that waits for this mutex is able to perceive the unexpected termination of a process when the first process exits without triggering the mutex.

The next step is to complete the "abandonment" problem test code for the event.

Process one:

[CPP]View PlainCopy
  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <windows.h>
  4. Const TCHAR str_event_name[] = TEXT ("event_morewindows");
  5. int main ()
  6. {
  7. printf ("The abandonment process for classic thread synchronization events is a \ n");
  8. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  9. HANDLE hevent = CreateEvent (NULL, False, False, Str_event_name); //Auto position not currently triggered
  10. printf ("event has been created, now press Y to trigger the event, press other key to terminate the process \ n");
  11. Char ch;
  12. scanf ("%c", &ch);
  13. if (ch! = ' y ')
  14. Exit (0); //Indicates that the process terminated unexpectedly
  15. SetEvent (hevent);
  16. printf ("event has been triggered \ n");
  17. CloseHandle (hevent);
  18. return 0;
  19. }

Process two:

[CPP]View PlainCopy
  1. #include <stdio.h>
  2. #include <windows.h>
  3. Const TCHAR str_event_name[] = TEXT ("event_morewindows");
  4. int main ()
  5. {
  6. printf ("The abandonment process for classic thread synchronization events two \ n");
  7. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  8. HANDLE hevent = OpenEvent (event_all_access, TRUE, str_event_name); //Open Event
  9. if (hevent = = NULL)
  10. {
  11. printf ("Open event failed \ n");
  12. return 0;
  13. }
  14. printf ("waiting .... \ n");
  15. DWORD dwresult = WaitForSingleObject (hevent, 10 * 1000); //Wait for event to be triggered
  16. switch (dwresult)
  17. {
  18. Case wait_abandoned:
  19. printf ("The process that owns the event terminated unexpectedly \ n");
  20. Break ;
  21. Case WAIT_OBJECT_0:
  22. printf ("The signal has been received \ n");
  23. Break ;
  24. Case Wait_timeout:
  25. printf ("no signal received within the specified time \ n");
  26. Break ;
  27. }
  28. CloseHandle (hevent);
  29. return 0;
  30. }

Event events test Result 1-normal end after a trigger event for a process:

Event Events Test Result 2-process an unexpected termination:

It can be seen that process two failed to perceive the unexpected termination of the process, stating that the event could not handle the "abandonment" issue.

Let's try the semaphore again below.

The "abandonment" problem test code for the semaphore:

Process one:

[CPP]View PlainCopy
  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <windows.h>
  4. Const TCHAR str_semaphore_name[] = TEXT ("semaphore_morewindows");
  5. int main ()
  6. {
  7. printf ("Classic thread synchronous semaphore abandonment process one \ n");
  8. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  9. HANDLE Hsemaphore = CreateSemaphore (NULL, 0, 1, str_semaphore_name); //Current 0 resources, maximum allowed 1 simultaneous access
  10. printf ("Semaphore has been created, now press Y to trigger the semaphore, press other key to terminate the process \ n");
  11. Char ch;
  12. scanf ("%c", &ch);
  13. if (ch! = ' y ')
  14. Exit (0); //Indicates that the process terminated unexpectedly
  15. ReleaseSemaphore (Hsemaphore, 1, NULL);
  16. printf ("The semaphore has been triggered \ n");
  17. CloseHandle (Hsemaphore);
  18. return 0;
  19. }

Process two:

[CPP]View PlainCopy
  1. #include <stdio.h>
  2. #include <windows.h>
  3. Const TCHAR str_semaphore_name[] = TEXT ("semaphore_morewindows");
  4. int main ()
  5. {
  6. printf ("Classic thread synchronous semaphore of abandonment process two \ n");
  7. printf ("-by Morewindows (http://blog.csdn.net/MoreWindows)--\n\n");
  8. HANDLE Hsemaphore = OpenSemaphore (semaphore_all_access, TRUE, str_semaphore_name); //Open signal Volume
  9. if (Hsemaphore = = NULL)
  10. {
  11. printf ("Open semaphore failed \ n");
  12. return 0;
  13. }
  14. printf ("waiting .... \ n");
  15. DWORD dwresult = WaitForSingleObject (Hsemaphore, 10 * 1000); //wait for the semaphore to be triggered
  16. switch (dwresult)
  17. {
  18. Case wait_abandoned:
  19. printf ("The process with semaphore has terminated unexpectedly \ n");
  20. Break ;
  21. Case WAIT_OBJECT_0:
  22. printf ("The signal has been received \ n");
  23. Break ;
  24. Case Wait_timeout:
  25. printf ("no signal received within the specified time \ n");
  26. Break ;
  27. }
  28. CloseHandle (Hsemaphore);
  29. return 0;
  30. }

Semaphore semaphore test Result 1-normal end of process one trigger semaphore

Semaphore semaphore test Result 2-process an unexpected termination

It can be seen that process two failed to perceive the process of an unexpected termination, indicating that the semaphore and the event can not deal with the "abandonment" problem.

Four Summary of the "abandonment" problem

The experiment in this paper shows that the mutex can deal with the situation of "abandonment", and the event and Semaphore cannot solve the situation.

The reason why the mutex can deal with the "abandonment" problem is that it has the concept of "thread ownership". In the system, once the thread end, the system will determine whether there is a mutex is occupied by the threads, if there is, the system will be the mutex object inside the thread ID number will be set to NULL, the recursive count is set to 0, which means that the mutex is no longer occupied by any thread, is in the trigger state. Other threads waiting for this mutex will be able to execute smoothly. As to how threads get Mutex "thread ownership", the MSDN description for--a thread obtainsownership of A mutex either by creating it with the BinitialownerPA Rameter set to TRUE or by specifying it handle in a call toone of the wait functions.

This is the end of the article, there are questions welcome message or send e-mail:[email protected]

Reprint please indicate source, original address: http://blog.csdn.net/morewindows/article/details/7823572

If you feel that this article is helpful, please click on the ' top ' support, your support is my greatest motivation to write, thank you.

The last extra: "Vernacular classic algorithm series of seven Big Sort" has been sorted out the form of e-books, Welcome to download,: http://download.csdn.net/detail/morewindows/4443208.

Seconds to kill multithreading 15th key segment, event, mutex, semaphore "abandonment" problem

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.