Why using a static variable is a bad idea to prevent multiple threads from entering a method at the same time

Often people do this, where we check a boolean value, if it is true, either sleep or return expecting that it will never happen that multiple threads will enter beyond this "gate".

Not true.

This is coded under the mistaken impression that every line of higher language code is executed as one statement and hence, it will never go beyond those lines if the next line sets the variable to true.

Because usually one line of higher language code even an i++ maps to multiple CPU instructions, given an adequately busy environment, this code will no longer "protect" the method. The only way to protect it is to use the lock statement.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory