Friday, May 31, 2013

Sasa.Atomics - Simpler, More Scalable Atomic Operations

This is the nineteenth post in my ongoing series covering the abstractions in Sasa. Previous posts:

The System.Threading namespace contains a number of useful abstractions for concurrent programming. The Interlocked static class in particular ought to be in every programmer's toolbox. However, the CompareExchange API doesn't always lend itself to the cleanest algorithms. Furthermore, under medium to high contention, even atomic compare-and-swap operations don't scale well.

Enter Sasa.Atomics, which provides a simpler API for atomic operations and implements the lightweight contention management scheme from the paper described above. Constant backoff contention management requires no state, and incurs virtually no overhead in low contention scenarios, and it scales quite well under medium to high contention.

Sasa.Atomics.Set

Sasa.Atomics.Set is a set of extension methods which perform a compare-and-exchange operation, and return true if the operation succeeds:

string o = "hello";
...
if (Atomics.Set(ref o, o + " world!", o))
    Console.WriteLine(o);
// output:
// hello world!

Sasa.Atomics.SetFailed

Sasa.Atomics.Set is a set of extension methods which perform a compare-and-exchange operation, and return true if the operation fails:

string o = "hello";
...
while (Atomics.SetFailed(ref o, o + " world!", o)) { }
// output:
// hello world!

No comments: