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: Shawn Erickson <email@hidden>
- Date: Fri, 2 Dec 2005 12:08:21 -0800
On 12/2/05, Shaun Wexler <email@hidden> wrote:
>
+ (MyGizmoClass*)sharedManager
>
{
>
if (sharedGizmoManager) {
>
return sharedGizmoManager;
>
}
>
>
@synchronized(self) {
>
if (sharedGizmoManager == nil) {
>
sharedGizmoManager = [[self alloc] init];
>
}
>
}
>
return sharedGizmoManager;
>
}
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.
-Shawn
_______________________________________________
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