1. The spin lock NSSpinLock, which is now deprecated and can’t be used, is defective and causes deadlocks. Visited when low priority thread lock and perform the task, then just the higher priority thread also visited lock, because of its priority is higher, so want to perform a task priority, so it will access the lock, and make the most of the CPU are used to access the lock busy etc., caused by lower priority thread does not have enough CPU time to perform the task, so caused the dead lock.
  2. Mutex p_thread_mutex,NSLock,@synthronized This order is sorted by performance and is the most commonly used mutex.
  3. Recursive lock NSRecursiveLock, which is a recursive lock, allows us to do multiple locks.
  4. NSCondition, conditional lock We can call wait to wait the current thread, call signal to continue the thread, or call broadcast to broadcast.
  5. Semaphore semphone can also be used as a mutex to a certain extent, it is suitable for more complex programming scenarios, and it is the lock with the highest performance after spin locks.
- (void)mutexLock{
    //pthread_mutex
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_lock(&mutex);
    pthread_mutex_unlock(&mutex);

    //NSLock
    NSLock *lock = [[NSLock alloc] init];
    lock.name = @"lock";
    [lock lock];
    [lock unlock];
    
    //synchronized
    @synchronized (self) {
        
    }
}

- (void)RecursiveLock{
    NSRecursiveLock *lock = [NSRecursiveLock alloc];
    [lock lock];
    [lock lock];
    
    [lock unlock];
}

- (void)conditionLock{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        condition = [[NSCondition alloc] init];
        [condition wait];
        NSLog(@"finish----");
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [NSThread sleepForTimeInterval:5.0];
        [condition signal];
    });
}

- (void)semaphore{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"semaphoreFinish---");
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [NSThread sleepForTimeInterval:5.0];
        dispatch_semaphore_signal(semaphore);
    });
}
Copy the code