I'm hacking together Cocos2D for a super short project, and I'm really impressed with how awesome it is. I really should have used it on a previous project, but instead rolled my own using the (awful?) Quartz classes.
I noticed a lot of singleton methods in the library, all of which could be slightly improved by (correctly) using double checked locking.
Here's these changes made to Director.m of release 0.8.2:
#include <libkern/OSAtomic.h>
+ (Director *)sharedDirector
{
if (!_sharedDirector)
{
@synchronized([Director class])
{
if (!_sharedDirector) { // double checked locking
id instance = [[self alloc] init];
OSMemoryBarrier(); // prevent reordering of assignment to static instance
_sharedDirector = instance; // assignment after barrier
}
}
}
return _sharedDirector;
}
+(id)alloc
{
@synchronized([Director class])
{
NSAssert(_sharedDirector == nil, @"Attempted to allocate a second instance of a singleton.");
return [super alloc];
}
// to avoid compiler warning
return nil;
}