Several commonly used locks iOS

  1. Spin lock
    NSSpinLock, it is now obsolete and can not be used, it is defective, it will cause a deadlock. When low priority thread to access the lock and execute the task, then just a high-priority thread also visited the lock because it has a higher priority, so the priority tasks, so it will not stop access to the lock, and makes the most of cpu used to access the lock busy, etc., resulting in low-priority thread does not have enough cpu opportunity to perform tasks, such causing a deadlock.
  2. Mutex
    p_thread_mutex, NSLock, @ synthronized This order is in accordance with the sort of performance, but also our common several mutex.
  3. Recursive lock
    NSRecursiveLock, it is recursive lock, which allows us multiple locks.
  4. Conditions lock
    NSCondition, lock condition we call the current thread wait method put into a wait state, when a signal calling method can allow the thread to continue, you can also call for broadcast method.
  5. Semaphore
    semphone a certain extent when the mutex may also be used, which applies to more complex scenarios programming logic, it is also thought that in addition to the highest spin lock locking performance.
- (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);
    });
}
复制代码

Reproduced in: https: //juejin.im/post/5cf6353ce51d45776031afb3

Guess you like

Origin blog.csdn.net/weixin_33892359/article/details/91417417