How to Design Multithreaded Applications to Avoid DeadlockLast reviewed: September 25, 1995Article ID: Q126768 |
The information in this article applies to:
SUMMARYDebugging a multithreaded application that deadlocks is challenging because the debugger cannot identify for you which thread owns which resource. You would have to track this information in your code. Because it is difficult to debug a deadlock situation, it is important to design your application to avoid deadlock. This article is a brief introduction to a very complex topic. There are references at the bottom of this article for additional information. The key point to keep in mind when designing a multithreaded program is that resources must always be requested in the same order.
MORE INFORMATIONThe Win32 API provides WaitForSingleObject() and WaitForMultipleObjects() for requesting resources with handles. You would use a different method to request other resources, depending on the resource type. Many deadlocks occur because resources are not requested in the same order by the application threads. For example:
To avoid this problem, identify all of your application's critical resources and order them from least precious to most precious. Design your code such that if a thread needs several resources, it requests them in order, starting with the least precious resource. Resources should be freed in the reverse order and as soon as it is possible. This is not a requirement to avoid deadlock, but it is good practice. In the example given above, suppose that resource B is more precious than resource A. Here's how the code would resolve the situation:
REFERENCESMSDN Development Library, "Detecting Deadlocks in Multithreaded Win32 Applications", by Ruediger Asche. For more information, refer to a good book on operating system design.
|
Additional reference words: 3.50 4.00 95 race condition
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |