Re: NSMapTable thread safety (with with ARC and weak objects)
Re: NSMapTable thread safety (with with ARC and weak objects)
- Subject: Re: NSMapTable thread safety (with with ARC and weak objects)
- From: Joar Wingfors <email@hidden>
- Date: Mon, 19 Nov 2012 09:53:18 -0800
On 19 nov 2012, at 04:05, James Montgomerie <email@hidden> wrote:
> On 16 Nov 2012, at 22:36, Quincey Morris <email@hidden> wrote:
>
>> On Nov 16, 2012, at 09:53 , James Montgomerie <email@hidden> wrote:
>>> 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?
>>
>> 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).
>
> Basically, I'm worried that the NSMapTable reacting to a weak object disappearing on a background thread is the moral equivalent of me mutating the NSMapTable on a background thread (turning the memory management issue into a data integrity issue). It seems like, since I don't see any documentation about it, there's a possibility that although ARCs handling of __weak is atomic and thread-safe, NSMapTable's reaction to the disappearance of a weak object it contains is not. From your answer, you would say that this is not the case?
Quincey is correct: The ObjectiveC runtime guarantees that weak pointers are nil:ed out in a thread safe way. Cocoa collection classes that offers weak keys / objects cope with this just fine. Nothing for you to worry about here.
Joar
_______________________________________________
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