Multithreading: a final example on how CompareExchange might help you

Published Sat, Jul 4 2009 16:31

In the last posts we’ve been poking around memory models, memory fences and other interesting things that might lead to the so called lock free programming. Before keep looking at how we can use those features from our C# code, I’d like to add one more example that shows how the interlocked operations might help you in the real world. Do you recall our implementation of the IAsyncResult interface?

At the time, we’ve used a lock for ensuring proper access and initialization of our manual reset event used for signaling the end of the operation. Now that we’ve met interlocked operations, we can improve that code and get rid of the lock. Let’s focus on the private GetEvtHandle method:

private ManualResetEvent GetEvtHandle() {
  var newEvt = new ManualResetEvent(false);
  if (Interlocked.CompareExchange(ref _evt, newEvt, null) != null) {
    newEvt.Close();
  }      
  if (_isCompleted) {
    _evt.Set();
  }      
  return _evt;
}

As you can see, we’ve replaced the lock with a CompareExchange method call for ensuring proper atomic update: if the _evt field is null, then set it to newEvt (which, if you recall our previous post on interlocked operations, will only happen when that value is null!). Since the method returns the old value, if we get anything different from null, then it means that some other thread already set the field to a valid value. When that happens, we need to clean up and close the manual reset event we’ve just created. And there you go: the lock is gone.

As you’ve probably guessed, This strategy can be adjusted to objects that implement the IDisposable interface and you can use it when the creation of new objects isn’t too expensive and you need to have only a single instance of an item (in other words, it might be a valid option for implementing singletons in multithreading scenarios).

And that’s it. Keep tuned for more on multithreading.

Filed under: ,

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover