@synchronized 再考察

核心是:将标示对象与锁建立关联。

线程

标识;

异常;

NSString *test = @"test";

@try {
    // Allocates a lock for test and locks it
    objc_sync_enter(test);
    test = nil;
} @finally {
    // Passed `nil`, so the lock allocated in `objc_sync_enter`
    // above is never unlocked or deallocated
    objc_sync_exit(test);   
}
 

int objc_sync_enter(id obj)

{

    int result = OBJC_SYNC_SUCCESS;

    if (obj) {

        SyncData* data = id2data(obj, ACQUIRE);

        require_action_string(data != NULL, done, result = OBJC_SYNC_NOT_INITIALIZED, "id2data failed");

        result = recursive_mutex_lock(&data->mutex);

        require_noerr_string(result, done, "mutex_lock failed");

    } else {

        // @synchronized(nil) does nothing

        if (DebugNilSync) {

            _objc_inform("NIL SYNC DEBUG: @synchronized(nil); set a breakpoint on objc_sync_nil to debug");

        }

        objc_sync_nil();

    }

done: 

    return result;

}

// 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* data = id2data(obj, RELEASE); 

        require_action_string(data != NULL, done, result = OBJC_SYNC_NOT_OWNING_THREAD_ERROR, "id2data failed");

        

        result = recursive_mutex_unlock(&data->mutex);

        require_noerr_string(result, done, "mutex_unlock failed");

    } else {

        // @synchronized(nil) does nothing

    }

原文地址:https://www.cnblogs.com/feng9exe/p/8567783.html