1.OSSpinLock(自旋锁,有优先级翻转问题已摒弃)
//导入头文件 #import <libkern/OSAtomic.h> //初始化锁 OSSpinLock lock = OS_SPINLOCK_INIT; //加锁 OSSpinLockLock(&_lock); //解锁 OSSpinLockUnlock(&_lock);
2.os_unfair_lock(iOS10以后替代OSSpinLock)
//导入头文件 #import <os/lock.h> //初始化锁 os_unfair_lock lock = OS_UNFAIR_LOCK_INIT; //加锁 os_unfair_lock_lock(&_lock); //解锁 os_unfair_lock_unlock(&_lock);
3.pthread_mutex_t(互斥锁)
//导入头文件 #import <pthread.h> //初始化锁属性 pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_NORMAL); //初始化锁 pthread_mutex_t mutex; pthread_mutex_init(&_mutex, &mutexattr); //加锁 pthread_mutex_lock(&_mutex); //解锁 pthread_mutex_unlock(&_mutex); //销毁 pthread_mutexattr_destroy(&_mutexattr); pthread_mutex_destroy(&_mutex);
4.NSLock、NSRecursiveLock
//初始化 self.lock = [[NSLock alloc]init]; //加锁 [self.lock lock]; //解锁 [self.lock unlock];
5.NSCondition、NSConditionLock(条件锁、处理线程依赖场景)
//初始化锁 self.condition = [[NSCondition alloc] init]; //加锁 [self.condition lock]; //条件 if (self.data.count == 0) { // 等待(这时锁是解开的状态) [self.condition wait]; } //信号(唤醒等待) [self.condition signal]; //解锁 [self.condition unlock];
6.dispatch_semaphore_t(信号量)
dispatch_semaphore_t semaphore = dispatch_semaphore_create(5); // 如果信号量的值 > 0,就让信号量的值减1,然后继续往下执行代码 // 如果信号量的值 <= 0,就会休眠等待,直到信号量的值变成>0,就让信号量的值减1,然后继续往下执行代码 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); dispatch_semaphore_signal(semaphore);
7.dispatch_queue_t(同步串行队列)
dispatch_queue_t sigQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL); dispatch_sync(self.sigQueue, ^{ ... });
8.@synchronized
@synchronized([self class]) { ... }
总结各种锁性能从高到低