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.