从不同的线程读取非原子弱指针是否安全,而不是取消分配对象?
通常,我知道只要可以同时访问,属性就应该是原子的,其中至少有一个是写操作。但我不得不怀疑ARC的写操作(将指针设置为nil)是否有点特殊。否则,我希望看到有关此可能问题的更多警告。也许弱指针隐含原子?
答案 0 :(得分:4)
很安全。访问弱指针和归零弱指针位于spinlock_lock和spinlock_unlock之间。
看一下运行时源代码 http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm
访问弱指针
id
objc_loadWeakRetained(id *location)
{
id result;
SideTable *table;
spinlock_t *lock;
retry:
result = *location;
if (!result) return nil;
table = SideTable::tableForPointer(result);
lock = &table->slock;
spinlock_lock(lock);
if (*location != result) {
spinlock_unlock(lock);
goto retry;
}
result = weak_read_no_lock(&table->weak_table, location);
spinlock_unlock(lock);
return result;
}
归零弱指针
void
objc_object::sidetable_clearDeallocating()
{
SideTable *table = SideTable::tableForPointer(this);
// clear any weak table items
// clear extra retain count and deallocating bit
// (fixme warn or abort if extra retain count == 0 ?)
spinlock_lock(&table->slock);
RefcountMap::iterator it = table->refcnts.find(this);
if (it != table->refcnts.end()) {
if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
weak_clear_no_lock(&table->weak_table, (id)this);
}
table->refcnts.erase(it);
}
spinlock_unlock(&table->slock);
}