April 26, 2009

Multiple Overlapping Critical Sections - the way to madness

If you have a manager class, and it has multiple worker threads - do your self a favor and ask someone to taser you before adding any additional critical sections beyond the first critical section.

I have seen the 23rd circle of hell, and it is a deadlock

most of the time it is easy to avoid, but then you get cocky & make mistakes.

Oh, this CS will protect this resource, and that CS will protect that resource. But then the thinkable happens
1 Someone else maintains the code and switches the use of the CS in one place
2 more and more code needs access to both resources simultaneously and you get an overlap effect - where you need something only a little.

In function A
Lock1
Do1
Lock2
Do2
Unlock2
Unlock1

In function B
Lock2
Do2
Lock1
Do1
Unlock1
Unlock2

well - this doesn't work. People forget, mix up the order and suddenly there is a chink in the armor of thread safety.

So next time ask your self: taser in the groin or multiple Critical Sections?

Yes, Taser please. The groin won't hurt as much.

Posted by Jason at 04:42 PM