The System.Threading.Interlocked class

When we reviewed race conditions in the previous chapter, we learned that even a simple increment operation consists of three separate actions. Although modern CPUs can perform such operations at once, it is necessary to make them safe to be used in concurrent programs.

The .NET Framework contains the System.Threading.Interlocked class that provides access to several operations that are atomic, which means that they are uninterruptible and appear to occur instantaneously to the rest of the system. These are the operations that the lock-free algorithms are based on.

Let's revise a race condition example and compare the locking and Interlocked class operations. First, we will use the traditional locking approach: ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.