On Dec 7, 2012, at 7:03 AM, Jeremy Pereira <jere...@jeremyp.net> wrote:
> On 12 Nov 2012, at 20:45, Greg Parker <gpar...@apple.com> 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     gpar...@apple.com     Runtime Wrangler



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to