Good Morning AskPerf! On Tuesday, we went over some very high-level concepts around synchronization mechanisms. Today, we’re going to briefly dig into one of those mechanisms, Interlocked Operations, in a little more depth. This isn’t going to be a programming exercise, it’s really targeted for our IT Admins and readers who don’t have a programming background (which includes me by the way!), so the content will be very high-level. OK, let’s get started …
Interlocked Operations are considered high-performance since they do not utilize operating system mechanisms to function. Instead they rely on hardware-based synchronization techniques. Interlocked operations are a way to update variables in an atomic manner. An operation is considered atomic if it is indivisible (not in a mathematical sense). During atomic operations threads cannot access variables that are in use (locked) by a different thread. Thus, if Thread A is reading the value of a variable, Thread B cannot change that value in the middle of that read operation. Similarly, if Thread A is writing to a variable, Thread B cannot read that value in the middle of Thread A’s write operation. If the operation were not atomic, then the possibility exists that Thread B could wind up reading part of the old value and part of the new value of the variable being accessed by Thread A.
In looking at the fundamentals of Interlocked Operations, we can see that they are both efficient and low-cost. Since the operations are supported at the hardware level, there is no wait state. Interlocked operations are performed immediately, and there is no user mode to kernel-mode transition. That having been said, Interlocked Operations are limited in that there is only so much that the native operations can do. More complex operations would require the use of alternate mechanisms – such as mutexes, which will be the topic of our next post.
With that, we’re at the end of this post – the resources listed below will be of more interest to the programmers among you. Until next time …
- A Hole in my Head: Creating your own Interlocked XXX Operation
- The Old New Thing : Interlocked operations don’t solve everything
- MSDN .NET Framework Developer’s Guide: Interlocked Operations