Nesting Critical Sections

Discussion to talk about software related topics only.
Post Reply
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Nesting Critical Sections

Post by SeeCwriter »

Is it a problem to nest critical sections?

Code: Select all

void func1()
{
    OSCriticalSectionObj protectthis( bus_access );
    // do stuff
    func2();
}

void func2()
{
    OSCriticalSectionObj protectthis( bus_access );
    // More stuff
    func3();
}

void func3()
{
    OSCriticalSectionObj protectthis( bus_access );
    // even more.
}
User avatar
pbreed
Posts: 1080
Joined: Thu Apr 24, 2008 3:58 pm

Re: Nesting Critical Sections

Post by pbreed »

Yes what you have described will work just fine.




The one area that will get you in trouble is if you have two differnt critical sections....

OSCriticalSectionObj protectthis( bus_access );

OSCriticalSectionObj protectthis( list_access);

In this case its REALLY important that you always enter in the same order....

IE if in one code path you have
OSCriticalSectionObj protectthis( bus_access );
.
.
.
.
OSCriticalSectionObj protectthis( list_access);



And in a differnt code path (in a differnt task)
OSCriticalSectionObj protectthis( list_access);
.
.
.
.

OSCriticalSectionObj protectthis( bus_access );


You will eventually end up hung in a dead lock....
So if ANY path can acquire two or more critical resources then any other path that acquires these resources MUST DO THEM IN THE SAME ORDER.

USER_ENTER_CRITICAL also counts as a critical resource.....for this ordering rule.
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Re: Nesting Critical Sections

Post by SeeCwriter »

That's good information. Thank you.
Post Reply