自旋锁
一、OSSpinLock
- OSSpinLock叫做”自旋锁”,等待锁的线程会处于忙等(busy-wait)状态,一直占用着CPU资源
- 目前已经不再安全,可能会出现优先级反转问题
- 如果等待锁的线程优先级较高,它会一直占用着CPU资源,优先级低的线程就无法释放锁
-
需要导入头文件#import <libkern/OSAtomic.h>
二、os_unfire_lock(不公平,跟踪汇编代码是休眠了,应该是互斥锁。苹果官方只说是low level lock低级锁)
- os_unfair_lock用于取代不安全的OSSpinLock ,从iOS10开始才支持
- 从底层调用看,等待os_unfair_lock锁的线程会处于休眠状态,并非忙等
- 需要导入头文件#import <os/lock.h>
互斥锁
一、pthread_mutex
mutex叫做”互斥锁”,等待锁的线程会处于休眠状态
pthread_mutex_t mutx;
pthread_mutexattr_t attr;
// 初始化锁属性
pthread_mutexattr_init(&attr);
//设置属性类型
#define PTHREAD_MUTEX_NORMAL 0
#define PTHREAD_MUTEX_ERRORCHECK 1
#define PTHREAD_MUTEX_RECURSIVE 2 //递归锁
#define PTHREAD_MUTEX_DEFAULT PTHREAD_MUTEX_NORMAL
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
// 初始化锁
pthread_mutex_init(&mutx, &attr);
// 销毁属性,使用完销毁
pthread_mutexattr_destroy(&attr);
//加锁
pthread_mutex_lock(&_ticketMutex);
//解锁
pthread_mutex_unlock(&_ticketMutex);
// 销毁锁,使用完销毁
pthread_mutex_destroy(&_ticketMutex);
@property (assign, nonatomic) pthread_mutex_t mutex;
@end
@implementation MutexDemo2
- (void)__initMutex:(pthread_mutex_t *)mutex
{
// 递归锁:允许同一个线程对一把锁进行重复加锁
// 初始化属性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
// 初始化锁
pthread_mutex_init(mutex, &attr);
// 销毁属性
pthread_mutexattr_destroy(&attr);
}
- (instancetype)init
{
if (self = [super init]) {
[self __initMutex:&_mutex];
}
return self;
}
/**
线程1:otherTest(+-)
otherTest(+-)
otherTest(+-)
线程2:otherTest(等待)
*/
- (void)otherTest
{
pthread_mutex_lock(&_mutex);
NSLog(@"%s", __func__);
static int count = 0;
if (count < 10) {
count++;
[self otherTest]; //递归锁 PTHREAD_MUTEX_RECURSIVE 允许同一个线程对一把锁加锁多次
}
pthread_mutex_unlock(&_mutex);
}
- (void)otherTest2
{
pthread_mutex_lock(&_mutex2);
NSLog(@"%s", __func__);
pthread_mutex_unlock(&_mutex2);
}
- (void)dealloc
{
pthread_mutex_destroy(&_mutex);
}