Is it valid to mutilayered a critical section?

79 views Asked by At

For example, is this valid?

CRITICAL_SECTION cs_A;
CRITICAL_SECTION cs_b;

::InitializeCriticalSection( &cs_A );
::InitializeCriticalSection( &cs_B );

::EnterCriticalSection( &cs_A );      // First level

/* do some stuff with A */

::EnterCriticalSection( &cs_B );        // Second level

/* do some stuff with A and B */

::LeaveCriticalSection( &cs_B );        // Second level

/* do some stuff with A */

::LeaveCriticalSection( &cs_A );      // First level

::DeleteCriticalSection( &cs_A );
::DeleteCriticalSection( &cs_B );

I would like to protect two very section of code with two critical sections. Can I do this?

Possible Duplicates: Is it valid to nest a critical section?

2

There are 2 answers

0
David Heffernan On BEST ANSWER

Whenever you have multiple locks and more than one lock may be held at one point in time, then you must make sure that the locks are always acquired in the same order. Failure to observe this can lead to deadlock.

This is a widely known and widely discussed rule. For instance, Use Lock Hierarchies to Avoid Deadlock.

0
marom On

I think your question is different form the one you mention, since you have two distinct critical sections.

Anyway you can nest them but you must take the care of enter/acquire them always in the same order, otherwise you risk a deadlock.