FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Architecture & Design
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
TABLE OF CONTENTS
November 06, 2007

Avoid Calling Unknown Code While Inside a Critical Section

(Page 3 of 4)

Example: Two Modules, But Only One Has Locks

Note that this kind of thing can happen even if both locks are in the same module, but control flow passes through another module so that you don't know what locks are taken. Consider the following modification, where the browser protects each page element using a separate mutex, which can be desirable to allow different parts of the page to be rendered concurrently:








// Example 3: Thread 1 of an alternative potential deadly embrace // class CoreBrowser { ... other methods ... private void RenderElements() { for( each PageElement e on the page ) { e.mut.lock(); // acquire exclusion on this page element try { DoRender( e ); // do our own default processing plugin.OnRender( e ); // let the plug-in have a // crack at it } finally { e.mut.unlock(); // and then release it } } } }

And consider a plug-in that does no locking of its own at all:

class MyPlugin { ... other methods ... public void OnRender( PageElement e ) { GuiCoord cPrev = browser.GetElemPosition( e.Previous() ); GuiCoord cNext = browser.GetElemPosition( e.Next() ); Use( e, cPrev, cNext ); // do something with the coords } }

But which calls back into:

class CoreBrowser { ... other methods ... public GuiCoord GetElemPosition( PageElement e2 ) { e2.mut.lock(); // acquire exclusion on this page element try { return FigureOutPositionFor( e2 ); } finally { e2.mut.unlock(); // and then release it } } }

The order of mutex acquisition is:

for each element e acquire e.mut acquire e.Previous().mut release e.Previous().mut acquire e.Next().mut release e.Next().mut release e.mut

Perhaps the most obvious issue is that any pair of locks on adjacent elements can be taken in both orders by Thread 1; so this cannot possibly be part of a correct lock hierarchy discipline.

Because of the interference of the plug-in code, which does not even have any locks of its own, this code has a latent deadlock if any other concurrently running thread (including perhaps another instance of Thread 1 itself) can take any two adjacent elements' locks in any order. The deadlock-proneness is inherent in the design, which fails to guarantee a rigorous ordering of locks. In this respect, the original Example 1 was better, even though its locking was coarse-grained and less friendly to concurrent rendering of different page elements.

Previous Page | 1 The Problem | 2 Example: Two Modules, One Lock Each | 3 Example: Two Modules, But Only One Has Locks | 4 Consequences: What Is "Unknown Code"? Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK