Re: How to implement readonly property
Re: How to implement readonly property
- Subject: Re: How to implement readonly property
- From: Greg Parker <email@hidden>
- Date: Fri, 07 Dec 2012 13:08:02 -0800
On Dec 7, 2012, at 7:03 AM, Jeremy Pereira <email@hidden> wrote:
> On 12 Nov 2012, at 20:45, Greg Parker <email@hidden> wrote:
>> There is something special about statically-allocated memory. Statically-allocated memory has always been zero for the life of the process. Dynamically-allocated memory may have been non-zero at some point in the past (i.e. if it was previously part of a now-freed allocation).
>>
>> The problem is your condition #2. If the memory was previously non-zero and you set it to zero, you need appropriate memory barriers on some architectures to prevent a race where the caller of dispatch_once() sees the old non-zero value. Neither dispatch_once() nor the malloc system nor the Objective-C runtime promise to provide the correct barriers.
>>
>> In some cases you might be able to add an appropriate memory barrier to your -init... method, assuming that no calls to dispatch_once() occur before then.
>>
>> In practice this is a difficult race to hit, but it's not impossible.
>
> Sorry, I'm a bit late to the party here but I've just read this and I don't understand it.
>
> If this race condition really exists, you couldn't assume that *any* instance variables of a newly initialised object have been zeroed out.
>
> What am I missing?
Your statement is missing the additional requirements to hit the race:
You can't assume that any instance variables of a newly initialized object have been zeroed out when
* you are reading them from threads other than the one that allocated the object and
* there is no synchronization between the allocating thread and the reading thread.
In ordinary code there is only one thread involved, or there is already some thread synchronization somewhere.
For example, the allocating thread acquires a lock before writing the new object's pointer somewhere that the reading thread can see it, and the reading thread takes the same lock before reading the object pointer. That lock is sufficient synchronization to make it work.
You'll only run into trouble if you are trying to use lock-free multiprocessing techniques and you don't use enough memory barriers.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
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