OC底层探索 - @synchronized

678 阅读5分钟
NSObject *obj = [NSObject new];
@synchronized (obj) {
    printf("HHHHH");
}

@synchronized 代码转换成 C++ 代码

{
    id _rethrow = 0;
    id _sync_obj = (id)obj;
    objc_sync_enter(_sync_obj);
    try {
        struct _SYNC_EXIT {
            // 构造函数
            _SYNC_EXIT(id arg) : sync_exit(arg) {}
            // 析构函数
            ~_SYNC_EXIT() {objc_sync_exit(sync_exit);}
            id sync_exit;
        }
        // 这里调用结构体的构造函数
        _sync_exit(_sync_obj);
        printf("HHHHH");
        // 等出了作用域后,会自动调用结构体的析构函数,
        // 析构函数中调用了 objc_sync_exit(sync_exit)
    } catch (id e) {
        // 异常
        _rethrow = e;
    }
}

所以 @synchronized 可用看作

// 加锁
objc_sync_enter(_sync_obj);
// 执行代码
printf("HHHHH");
// 解锁
objc_sync_exit(sync_exit);

进入 objc源码查看上面2个方法:

objc_sync_enter(_sync_obj)

// Begin synchronizing on 'obj'. 
// Allocates recursive mutex associated with 'obj' if needed.
// Returns OBJC_SYNC_SUCCESS once lock is acquired.  
int objc_sync_enter(id obj)
{
    int result = OBJC_SYNC_SUCCESS;

    if (obj) {
        // 获取相应的 SyncData
        SyncData* data = id2data(obj, ACQUIRE);
        ASSERT(data);
        // 加锁
        data->mutex.lock();
    } else {
        // @synchronized(nil) does nothing
        // 当 `@synchronized(nil)` 时,什么也不做
        if (DebugNilSync) {
            _objc_inform("NIL SYNC DEBUG: @synchronized(nil); set a breakpoint on objc_sync_nil to debug");
        }
        objc_sync_nil();
    }
    return result;
}

objc_sync_exit(sync_exit);

// End synchronizing on 'obj'. 
// Returns OBJC_SYNC_SUCCESS or OBJC_SYNC_NOT_OWNING_THREAD_ERROR
int objc_sync_exit(id obj)
{
    int result = OBJC_SYNC_SUCCESS;

    if (obj) {
        // 获取相应的 SyncData
        SyncData* data = id2data(obj, RELEASE); 
        if (!data) {
            result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR;
        } else {
            // 解锁
            bool okay = data->mutex.tryUnlock();
            if (!okay) {
                result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR;
            }
        }
    } else {
        // 当 `@synchronized(nil)` 时,什么也不做
        // @synchronized(nil) does nothing
    }
    
    return result;
}

观察上面2个函数的源码,我们可以发现

  1. @synchronized(nil)时,同步锁不会生效,相当于未加锁
  2. objc_sync_enter(_sync_obj) 中是 SyncData* data = id2data(obj, ACQUIRE);;
    objc_sync_exit(sync_exit) 中是 SyncData* data = id2data(obj, RELEASE); 

所以应该研究 SyncDataid2data(objc, ACQUIRE/RELEASE)

SyncData

typedef struct alignas(CacheLineSize) SyncData {
    struct SyncData* nextData;
    DisguisedPtr<objc_object> object;
    int32_t threadCount;  // number of THREADS using this block
    recursive_mutex_t mutex;
} SyncData;

观察 SyncData 结构体,
nextData 变量,是 SyncData 类型指针。所以,SyncData 可以构成一个单向链表。
object变量,是对 @synchronized参数的封装。
threadCount变量,使用该block的线程数的计数。
mutex变量,递归互斥锁。

id2data 函数

TLS ( Thread Local Storage ): TLS就是线程局部存储,是操作系统为线程单独提供的私有空间,能存储只属于当前线程的一些数据

id2data 返回当前线程中 object 对应的 SyncData

static SyncData* id2data(id object, enum usage why)
{
    // os_unfair_lock 类型的锁
    spinlock_t *lockp = &LOCK_FOR_OBJ(object);// #define LOCK_FOR_OBJ(obj) sDataLists[obj].lock
    // 二级指针,类似链表的头指针
    SyncData **listp = &LIST_FOR_OBJ(object);// #define LIST_FOR_OBJ(obj) sDataLists[obj].data
    /*
    // 全局的 sDataLists 哈希表
    static StripedMap<SyncList> sDataLists;
    StripedMap是用来缓存带spinlock锁能力的类或结构体的哈希表,
    在真机上里面有8张SyncList表,模拟器上里面有64张SyncList表
     struct SyncList {
         SyncData *data; // 数据
         spinlock_t lock; // 锁
     }
     */
    // 返回结构体指针
    SyncData* result = NULL;

#if SUPPORT_DIRECT_THREAD_KEYS
    /* 从当前线程 TLS 中的 fast cache 中查找 SyncData */
    // Check per-thread single-entry fast cache for matching object
    // 检查每个线程的单条目快速缓存是否匹配对象
    bool fastCacheOccupied = NO;
    SyncData *data = (SyncData *)tls_get_direct(SYNC_DATA_DIRECT_KEY);
    if (data) {
        fastCacheOccupied = YES;
        // 如果找到 data的object == object
        if (data->object == object) {
            // Found a match in fast cache.
            uintptr_t lockCount;
            // 赋值给 result
            result = data;
            // 获取锁的计数
            lockCount = (uintptr_t)tls_get_direct(SYNC_COUNT_DIRECT_KEY);
            if (result->threadCount <= 0  ||  lockCount <= 0) {
                _objc_fatal("id2data fastcache is buggy");
            }

            switch(why) {
            // 获取的时候走这个分支
            case ACQUIRE: {
                // 锁的计数 ++
                lockCount++;
                tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount);
                break;
            }
            // 释放的时候走这个分支
            case RELEASE:
                // 锁的计数 --
                lockCount--;
                tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)lockCount);
                // 如果锁数目等于0
                if (lockCount == 0) {
                    // 从缓存中删除
                    // remove from fast cache
                    tls_set_direct(SYNC_DATA_DIRECT_KEY, NULL);
                    // 使用该block的线程数的计数 -1
                    // atomic because may collide with concurrent ACQUIRE
                    OSAtomicDecrement32Barrier(&result->threadCount);
                }
                break;
            case CHECK:
                // do nothing
                break;
            }
            return result;
        }
    }
#endif

    /* 从当前线程 TLS 中的 cache 中查找 SyncData */
    // Check per-thread cache of already-owned locks for matching object
    // 检查已拥有锁的每个线程缓存,以查找匹配的对象,从 TLS 中获取 SyncCache
    SyncCache *cache = fetch_cache(NO);
    if (cache) {
        unsigned int i;
        // 遍历 cache 中的 SyncCacheItem
        for (i = 0; i < cache->used; i++) {
            SyncCacheItem *item = &cache->list[i];
            // 判断 有没有跟现在加锁的 object 相等的数据,直到找到或找完
            if (item->data->object != object) continue;
            // 找到后 赋值给 result
            // Found a match.
            result = item->data;
            if (result->threadCount <= 0  ||  item->lockCount <= 0) {
                _objc_fatal("id2data cache is buggy");
            }

            switch(why) {
            // 获取的时候走这个分支
            case ACQUIRE:
                // item 中锁的计数 ++
                item->lockCount++;
                break;
            // 释放的时候走这个分支
            case RELEASE:
                // item 中锁的计数 --
                item->lockCount--;
                // 如果锁数目等于0
                if (item->lockCount == 0) {
                    // 把chche中记录的这个item移除
                    // remove from per-thread cache
                    cache->list[i] = cache->list[--cache->used];
                    // 使用该block的线程数的计数 -1
                    // atomic because may collide with concurrent ACQUIRE
                    OSAtomicDecrement32Barrier(&result->threadCount);
                }
                break;
            case CHECK:
                // do nothing
                break;
            }
            // 返回 result
            return result;
        }
    }

    // Thread cache didn't find anything.
    // Walk in-use list looking for matching object
    // Spinlock prevents multiple threads from creating multiple 
    // locks for the same new object.
    // We could keep the nodes in some hash table if we find that there are
    // more than 20 or so distinct locks active, but we don't do that now.
    lockp->lock();
    /* 从 SyncListe 中查找 SyncData */
    {
        SyncData* p;
        SyncData* firstUnused = NULL;
        for (p = *listp; p != NULL; p = p->nextData) {
            // 如果找到 , goto don
            if ( p->object == object ) {
                result = p;
                // atomic because may collide with concurrent RELEASE
                OSAtomicIncrement32Barrier(&result->threadCount);
                goto done;
            }
            if ( (firstUnused == NULL) && (p->threadCount == 0) )
                firstUnused = p;
        }
        // 没有找到,但是是 RELEASE/CHECK,也去 goto don
        // no SyncData currently associated with object
        if ( (why == RELEASE) || (why == CHECK) )
            goto done;
            
        // 没有找到, 且表不为空 ACQUIRE(第一次加锁),加入进链表,
        // an unused one was found, use it
        if ( firstUnused != NULL ) {
            result = firstUnused;
            result->object = (objc_object *)object;
            result->threadCount = 1;
            goto done;
        }
    }

    // Allocate a new SyncData and add to list.
    // XXX allocating memory with a global lock held is bad practice,
    // might be worth releasing the lock, allocating, and searching again.
    // But since we never free these guys we won't be stuck in allocation very often.
    // 没有找到, 且表为空,加入进链表
    posix_memalign((void **)&result, alignof(SyncData), sizeof(SyncData));
    result->object = (objc_object *)object;
    result->threadCount = 1;
    new (&result->mutex) recursive_mutex_t(fork_unsafe_lock);
    result->nextData = *listp;
    *listp = result;

 done:
    lockp->unlock();
    if (result) {
        // Only new ACQUIRE should get here.
        // All RELEASE and CHECK and recursive ACQUIRE are 
        // handled by the per-thread caches above.
        if (why == RELEASE) {
            // Probably some thread is incorrectly exiting 
            // while the object is held by another thread.
            return nil;
        }
        if (why != ACQUIRE) _objc_fatal("id2data is buggy");
        if (result->object != object) _objc_fatal("id2data is buggy");

#if SUPPORT_DIRECT_THREAD_KEYS
        // 如果 fast cache 中没有,加入 fast cache
        if (!fastCacheOccupied) {
            // Save in fast thread cache
            tls_set_direct(SYNC_DATA_DIRECT_KEY, result);
            tls_set_direct(SYNC_COUNT_DIRECT_KEY, (void*)1);
        } else 
#endif
        {
            // 加入线程缓存
            // Save in thread cache
            if (!cache) cache = fetch_cache(YES);
            cache->list[cache->used].data = result;
            cache->list[cache->used].lockCount = 1;
            cache->used++;
        }
    }
    return result;
}

_objc_pthread_data

// objc per-thread storage
typedef struct {
    struct _objc_initializing_classes *initializingClasses; // for +initialize
    struct SyncCache *syncCache;  // for @synchronize
    struct alt_handler_list *handlerList;  // for exception alt handlers
    char *printableNames[4];  // temporary demangled names for logging
    const char **classNameLookups;  // for objc_getClass() hooks
    unsigned classNameLookupsAllocated;
    unsigned classNameLookupsUsed;

    // If you add new fields here, don't forget to update 
    // _objc_pthread_destroyspecific()

} _objc_pthread_data;

typedef struct SyncCache {
    unsigned int allocated;
    unsigned int used;
    SyncCacheItem list[0];
} SyncCache;

typedef struct {
    SyncData *data;
    // 这个线程锁定这个block的次数
    unsigned int lockCount;  // number of times THIS THREAD locked this block 

} SyncCacheItem;

为什么 @synchronized 可以多线程递归调用?

通过源码我们可以知道, 对每个@synchronized(obj) 每个线程都有一个对应objSyncData ,其中有recursive_mutex_t mutex 递归锁,并不是只使用一锁来实现的。每个线程使用自己的递归锁来进行递归调用的。

为什么要使用StripedMap<SyncList>来管理 SyncList 表?

如果说系统在全局只初始化一张 SyncList 表用来管理所有对象的加锁和解锁操作,其实也是可以。只是效率会很慢,因为每个对象在操作这个 SyncList 表的时候,都需要等待其他对象操作完解锁之后才能进行。或者说,系统为每一个对象都创建一个 SyncList 表,其实也是可以的,只是内存的消耗会非常大。所以,苹果就用这个 StripedMap 来解决这个问题,提前准备一定张数的表放这里,然后在调用的时候均匀的进行分配。