Re: Is Apple's singleton sample code correct?
Re: Is Apple's singleton sample code correct?
- Subject: Re: Is Apple's singleton sample code correct?
- From: Shaun Wexler <email@hidden>
- Date: Fri, 2 Dec 2005 12:40:44 -0800
On Dec 2, 2005, at 12:08 PM, Shawn Erickson wrote:
Doing the "if(sharedGizmoManager)" check outside of the synchronized
block can be dangerous because it assumes that the storing of a
pointer in the sharedGizmoManager is atomic. Atomic depends on what
the architecture is capable of given the width of the pointer.
In other words only a part of the sharedGizmoManager point could be
written out from "[[self alloc] init]" when that thread gets
interrupted and another thread comes along and does the
"if(sharedGizmoManager)" check. That other thread would see that
sharedGizmoManager is not nil but the pointer hasn't fully been
written so the pointer is invalid.
That's technically correct, but a bit of a stretch... ;)
I believe the ABI (or CPU doc) states that size-aligned accesses are
atomic per-cycle. Hopefully the compiler maintains native alignment,
but you can ensure it (and safely assume it is 32-bits, for app's on
Mac OS X) using:
typedef id alignedID __attribute__ ((aligned (4)));
static alignedID mySingleton = nil;
--
Shaun Wexler
MacFOH
http://www.macfoh.com
"If God dropped acid, would he see people?" - Steven Wright
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden