Thursday, January 6, 2011

Why would you use lock if you can take a bool...?

Some developers have perfect in-depth knowledge about multithreading and synchronization as the following piece of C#-code shows:


while(dangerous)
;
dangerous = true;

// operations in critical section here...

dangerous = false;


... as you can see, the people who invented lock(...) just think way too complicated - in reality it's much easier! You only have to know that one of the very important properties of bool variables is that several lines of code that use the same variable are compiled down to a single atomic operation :-)
Ah - and I forgot to mention the other important property: in case of an exception it is guaranteed that all bools are automatically set to false during stack unrolling... :-)

No comments:

Post a Comment