Let's say i have a class Foo and it has a static member variable named Count ( type is integer). This variable was used in a multithreaded application and i was using lock synchronization mechanism before doing any read/write to this variable. As I am reading this article Volatile I am getting the impression that i can remove all those locks around this variable and just use volatile keyword at declaration of this variable. That should take care of all the synchnronization related stuff. Is this correct? What are the pros and cons to this approach?
I can remove all those locks around this variable and just use volatile keyword at declaration of this variable. That should take care of all the synchnronization related stuff. Is this correct?
Maybe. Maybe not. Getting multithreaded code correct is extremely difficult. Getting low-lock multithreaded code correct is best left to experts.
What are the pros and cons to this approach?
The pros are that it can be several nanoseconds faster to avoid the lock. The cons are, if you get low-lock programming wrong then your program looks like it works just fine, and then has bizarre failure modes that are impossible to debug or reproduce.
You should only go with a low-lock solution when your performance analysis has led you to conclude that a low-lock solution is the only way to attain the performance goal your customers require you to attain. And you should only go with a low-lock solution when you have a thorough and deep understanding of every optimization that every possible CPU your program will ever run on can perform on low-lock code. You'll need to deeply understand the memory model that is guaranteed to you by the CLR, what is guaranteed by hardware, and what all the differences are.
I don't possess this understanding myself. That's why I don't write anything except the most trivial low-lock code, and I have what little low-lock code I do write carefully reviewed by industry-leading experts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With