Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

Getting mutex free code right.

Posted by peeterjoot on May 4, 2011

Code to do mutex free manipulation is easy to get wrong.

Here’s a perfect example, code written to atomically set-if-bigger.

do {
	if ( newValue > *pAtomic )
	{
		oldValue = *pAtomic ;
	}
	else
	{ 		
		break ;
	}
} while( OLD_DID_NOT_MATCH == compareAndSwap( oldValue, newValue, pAtomic ) ) ;

I leave it as an exercise to the reader to find the bug.

This particular bug sat there, mostly behaving correctly since it was infrequently called, and “only” took about three or four years to find. It was found the hard way, in a test scenario with just enough concurrency and just enough “luck”. I think that the code that indirectly called this went through about 10 iterations of debug code over the years, although it didn’t help that we had to fix our own share of bugs in the process, before all that was left was the atomic bug.

Advertisements

3 Responses to “Getting mutex free code right.”

  1. Hasan said

    I’d guess there should be one access to *pAtomic? So save it to a temporary variable, and compare newValue to that and assign the same to oldValue.

  2. Hasan said

    Sorry…so delete the comment then! đŸ˜‰

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: