A critical section is a section of code in which, if more than one thread was doing this at the same time, they could interfere with each other, so as to cause an incorrect result or another malfunction. Imagine a simple banking procedure to process a check:
doCheck (writer, recipient, amount) { if (amount < 0) return DIAF; balance = getBalance( writer ); if (balance < amount) return NSF; setBalance( recipient, getBalance(recipient) + amount ); setBalance( writer, balance - amount ); }
Now imagine that my balance is $ 11,000, and I wrote two checks:
John, ColumbiaHouse, $0.01 John, MrsJohn, $10,000
Now our bank processes so many checks that the ace programmer DonaldJavaSlump adds threads, because it’s performance - but he doesn’t know about critical sections, so thread 1 starts processing the first check:
if (amount < 0) return DIAF; // (0.01 < 0)? OK balance = getBalance(John) // $11,000 if (balance < amount) return NSF; // (11,000 < 0.01?) OK setBalance( ColumbiaHouse, ... // KaChing! ColumbiaHouse gets paid
and now thread 2 starts through the same second processing code section:
if (amount < 0) return DIAF; // (10,000 < 0)? OK balance = getBalance( John ); // $11,000 (still!) if (balance < amount) return NSF; // (11,000 < 10,000?) OK setBalance( MrsJohn, ... // KaChing! MrsJohn gets paid setBalance( John, balance - amount ); // my balance is now $1,000 :(
and then thread 1 is nearing completion of its work:
setBalance( John, balance - amount ); // now balance is $10,999.99!!! :)
Now John and Mrs. John are happy again and embark on a free money cruise.