I have the following scenario in my code (C# .NET 4):
I have a boolean variable that is initialized to false:
bool b = false;
now I am instantiating number of threads, that each one of them need to read the value of b. the first thread to read b – should change its value to true (and do some logic…), and the others should do nothing. Do I need to use sync mechanism for ‘b’ while reading its value, or can I lock it only while setting its value to true?
This should boost my performance, but I am wondering id its safe..
So the requirements are:
boolvariablefalsevalue it should change it totrueand perform additional worktruevalue then nothing else should happenSo the code would look like:
This, of course, is not safe if there are multiple threads executing
DoSomethingand the intention is thatDoExtraStuffshould only be executed once. The problem is that the threads will race on the read and write ofb.You really need to make the read and write to
batomic. This can be done using thelockkeyword.There is an alternate pattern using a CAS operation via
Interlocked.CompareExhange. Unfortunately, there is no overload that accepts abool, but if you are willing to change thatboolto anintthe following would also work.