• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Is Apple's singleton sample code correct?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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
References: 
 >RE: Is Apple's singleton sample code correct? (From: Jeff Laing <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: mmalcolm crawford <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: Dietmar Planitzer <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: Shaun Wexler <email@hidden>)
 >Re: Is Apple's singleton sample code correct? (From: Shawn Erickson <email@hidden>)

  • Prev by Date: Re: Is Apple's singleton sample code correct?
  • Next by Date: Re: Is Apple's singleton sample code correct?
  • Previous by thread: Re: Is Apple's singleton sample code correct?
  • Next by thread: Re: Is Apple's singleton sample code correct?
  • Index(es):
    • Date
    • Thread