I\'ve been experimenting with multi threading and parallel processing and I needed a counter to do some basic counting and statistic analysis of the speed of the processing.
There are a few different ways to define "cost". There is the actual overhead of obtaining and releasing the lock; as Jake writes, that's negligible unless this operation is performed millions of times.
Of more relevance is the effect this has on the flow of execution. This code can only be entered by one thread at a time. If you have 5 threads performing this operation on a regular basis, 4 of them will end up waiting for the lock to be released, and then to be the first thread scheduled to enter that piece of code after that lock is released. So, your algorithm is going to suffer significantly. How much so depends on the algorithm and how often the operation is called.. You can't really avoid it without introducing race conditions, but you can ameliorate it by minimizing the number of calls to the locked code.