Re: How to implement readonly property
Re: How to implement readonly property
- Subject: Re: How to implement readonly property
- From: Kyle Sluder <email@hidden>
- Date: Sat, 08 Dec 2012 23:27:47 -0800
On Sat, Dec 8, 2012, at 05:27 PM, Richard Heard wrote:
> Greg,
>
> So, from what you are saying, either of these snippets should be valid,
> right?
>
> > +(id)sharedInstance{
> > static id _sharedInstance = nil;
> >
> > if (!_sharedInstance){
> > @synchronized([self class]){
> > if (!_sharedInstance){
> > id sharedInstance = [[super allocWithZone:NULL] init];
> > OSMemoryBarrier();
> > _sharedInstance = sharedInstance;
> > }
> > }
> > }
> >
> > OSMemoryBarrier();
> > return _sharedInstance;
> > }
Greg's advice notwithstanding, I'm not certain this is correct. You need
to ensure Thread B's read of _sharedInstance is atomic with respect to
both Thread A's assignment to _sharedInstance *and* the construction of
the object to which _sharedInstance points. By putting the always-taken
memory barrier _after_ the conditional, you've failed to guarantee the
order of Thread B's branch relative to Thread A's assignment to
_sharedInstance.
The first example of corrected double-checked locking in this paper
issues the memory barrier before reading the value of _sharedInstance
from outside the critical section:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
If dispatch_once() really is unsuitable for use with a dispatch_once_t
stored in Objective-C instance storage, then the correct example in the
paper I've cited might be a sufficient workaround.
Of course, it's just as simple to push the entire contents of your
+sharedInstance method into the critical section and not have to worry
about memory barriers at all by relying on the coarser, higher-order
synchronization primitive @synchronized provides. The performance hit is
probably negligible.
--Kyle Sluder
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden