On Nov 16, 2012, at 09:53 , James Montgomerie <ja...@montgomerie.net> wrote:

> How thread safe is NSMapTable?
> 
> I know that's a pretty nebulous question, so more concretely:
> 
> Let's assume I'm using ARC.  If I create an NSMapTable with "[NSMapTable 
> strongToWeakObjectsMapTable]", is it safe to put objects into it that might 
> be referenced from, and perhaps deallocated on, a background thread?  
> Specifically, might I get a half-deallocated or retain-count-zero object back 
> from -objectForKey: if a 'right' race condition happens?  
> 
> Does the answer to this change if I guarantee that the NSMapTable itself (but 
> not the objects it contains) will be used only on the a single thread?

It's a mutable collection, and it's listed in the thread safety guide as 
"unsafe".

Specifically, that means you shouldn't be modifying a map table (in the sense 
of adding, replacing or deleting objects) while a different thread might be 
accessing the map table, not even just reading it. This is not a memory 
management issue, but rather a data integrity issue.

As for the objects themselves, what do you mean by "half-deallocated" or 
"retain-count-zero"? If an object is strongly referenced in the map table 
(whether as a key or a value), its lifetime can't end before it's removed from 
the table. If an object is ARC-weakly referenced, the reference can go to zero 
at any time, but that happens in a thread-safe manner. Anyway, because this is 
ARC, if you get a non-nil value from the table, the referenced object is kept 
alive while you have the reference (until the end of the referencing scope, 
assuming you do nothing to prolong the lifetime beyond that point).


_______________________________________________

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