【问题标题】:Is it safe to read a weak pointer while it's being deallocated?在释放弱指针时读取它是否安全?
【发布时间】:2023-04-09 06:34:02
【问题描述】:

从与正在释放对象的线程不同的线程读取非原子弱指针是否安全?

一般来说,我知道属性应该是原子的,只要有可能同时访问,至少其中一个是写操作。但是我不得不怀疑ARC的写操作(将指针设置为nil)是否有些特殊。否则,我会看到更多关于这个可能问题的警告。也许弱指针是隐式原子的?

【问题讨论】:

    标签: objective-c automatic-ref-counting race-condition


    【解决方案1】:

    这是安全的。访问弱指针和清零弱指针介于 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);
    }
    

    对象释放流程 https://stackoverflow.com/a/14854977/629118

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 2012-12-17
      • 2017-05-15
      • 2019-01-17
      • 1970-01-01
      • 2011-06-02
      • 2012-09-07
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多