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:14:15 -0800
On 12/2/05, Shawn Erickson <email@hidden> wrote:
>
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.
I meant to add that if calling sharedManager is found to be a hot
method then likely the best solution is to simply not do the lazy
allocation but instead allocate the singleton during application
initialization (or in main) so it is ready for callers of
sharedManager.
Of course this assume you have the desire (likely smart to do) to
allow sharedManager to be called from arbitrary threads, if not then
no synchronization is needed and lazy allocation is just fine.
_______________________________________________
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