多线程-锁

dispatch_sync:立马在当前线程同步执行任务。
dispatch_async:不要求立马在当前线程同步执行任务。
使用sync函数往当前串行队列中添加任务,会卡主当前的串行队列。

  • 死锁:使用sync函数往当前串行队列中添加任务,会卡主当前的串行队列
  • 多线程安全隐患

1、一块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源。比如多个线程访问同一个对象、同一个变量、同一个文件
2、当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题

✔️ 解决方案:使用线程同步技术

线程同步,就是协调步调,按照预定的先后次序进行运行。常见的线程同步技术:加锁。

  • 递归锁:允许同一个线程对一把锁进行重复加锁

  • 1、OSSpinLock叫做”自旋锁”,等待锁的线程会处于忙等(busy-wait)状态,一直占用着CPU资源
    目前已经不再安全,可能会出现优先级反转问题:CPU分配时间给优先级高的
    如果等待锁的线 程优先级较高,它会一直占用CPU资源,优先级低的线程就无法释放锁
    需要导入头文件#import

#import "OSSpinLockDemo.h"
#import 

@interface OSSpinLockDemo ()
@property(nonatomic, assign) OSSpinLock moneyLock;
@property(nonatomic, assign) OSSpinLock ticketLock;
@end

@implementation OSSpinLockDemo
- (instancetype)init{
    if (self = [super init]) {
        self.moneyLock = OS_SPINLOCK_INIT;
        self.ticketLock = OS_SPINLOCK_INIT;
    }
    return self;
}

- (void)__saveMoney{
    OSSpinLockLock(&_moneyLock);
    [super __saveMoney];
    OSSpinLockUnlock(&_moneyLock);
}

- (void)__drawMoney{
    OSSpinLockLock(&_moneyLock);
    [super __drawMoney];
    OSSpinLockUnlock(&_moneyLock);
}

- (void)__saleTicket{
    OSSpinLockLock(&_moneyLock);
    [super __saleTicket];
    OSSpinLockUnlock(&_moneyLock);
}
@end

  • 2、os_unfair_lock用于取代不安全的OSSpinLock ,从iOS10开始才支持
    从底层调用看,等待os_unfair_lock锁的线程会处于休眠状态,并非忙等
    需要导入头文件#import
#import "OSUnfairLockDemo.h"
#import 
#import 

@interface OSUnfairLockDemo ()
@property (nonatomic,  assign) os_unfair_lock moneyLock;
@property (nonatomic,  assign) os_unfair_lock ticketLock;
@end

@implementation OSUnfairLockDemo

- (instancetype)init{
    if (self == [super init]) {
        self.moneyLock = OS_UNFAIR_LOCK_INIT;
    }
    return self;
}
- (void)__saveMoney{
    os_unfair_lock_lock(&_moneyLock);
    [super __saveMoney];
    os_unfair_lock_unlock(&_moneyLock);
}

- (void)__saleTicket{
    os_unfair_lock_lock(&_ticketLock);
    [super __saleTicket];
    os_unfair_lock_unlock(&_ticketLock);
}

- (void)__drawMoney{
    os_unfair_lock_lock(&_ticketLock);
    [super __drawMoney];
    os_unfair_lock_unlock(&_ticketLock);
}
@end
  • 3、mutex叫做”互斥锁”,等待锁的线程会处于休眠状态
    需要导入头文件#import
#import "MutexDemo.h"
#import 

@interface MutexDemo ()
@property (nonatomic, assign) pthread_mutex_t moneyMutex;
@property (nonatomic, assign) pthread_mutex_t ticketMutex;
@end

@implementation MutexDemo

- (void)__initMutex:(pthread_mutex_t *)mutex{
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
    pthread_mutex_init(mutex, &attr);
    pthread_mutexattr_destroy(&attr);
}

- (instancetype)init{
    if (self = [super init]) {
//        self.mutex = PTHREAD_MUTEX_INITIALIZER;
        [self __initMutex:&_moneyMutex];
        [self __initMutex:&_ticketMutex];
    }
    return self;
}

- (void)__saveMoney{
    pthread_mutex_lock(&_moneyMutex);
    [super __saveMoney];
    pthread_mutex_unlock(&_moneyMutex);
}

- (void)__drawMoney{
    pthread_mutex_lock(&_moneyMutex);
    [super __drawMoney];
    pthread_mutex_unlock(&_moneyMutex);
}

- (void)__saleTicket{
    pthread_mutex_lock(&_ticketMutex);
    [super __saleTicket];
    pthread_mutex_unlock(&_ticketMutex);
}
@end
  • 4、NSLock是对mutex普通锁的封装。
#import "NSLockDemo.h"
#import 

@interface NSLockDemo ()
@property (nonatomic, strong) NSLock *moneyLock;
@property (nonatomic, strong) NSLock *ticketLock;
@end

@implementation NSLockDemo


- (instancetype)init{
    if (self = [super init]) {
        //        self.mutex = PTHREAD_MUTEX_INITIALIZER;
        self.moneyLock = [[NSLock alloc] init];
        self.ticketLock = [[NSLock alloc] init];
    }
    return self;
}

- (void)otherTest{
    NSLog(@"%s",__func__);
    [self otherTest];
}

- (void)otherTest2{

}

- (void)__saveMoney{
    [self.moneyLock lock];
    [super __saveMoney];
    [self.moneyLock unlock];
}

- (void)__drawMoney{
    [self.ticketLock lock];
    [super __drawMoney];
    [self.ticketLock unlock];
}

- (void)__saleTicket{
    [self.ticketLock lock];
    [super __saleTicket];
    [self.ticketLock unlock];
}
@end
  • 5、NSRecursiveLock也是对mutex递归锁的封装,API跟NSLock基本一致
  • 6、NSCondition是对mutex和cond的封装
#import "NSConditionDemo.h"
#import 

@interface NSConditionDemo ()
@property (nonatomic, strong) NSCondition *conditionLock;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation NSConditionDemo

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (instancetype)init{
    if (self = [super init]) {
        self.conditionLock = [[NSCondition alloc] init];
    }
    return self;
}

- (void)otherTest{
    [[[NSThread alloc] initWithTarget:self selector:@selector(__add) object:nil] start];
    [[[NSThread alloc] initWithTarget:self selector:@selector(__remove) object:nil] start];
}

- (void)__add{
    [self.conditionLock lock];
    [self.dataArray addObject:@"test"];
    NSLog(@"添加了元素");
    
    [self.conditionLock unlock];
}

- (void)__remove{
    [self.conditionLock lock];
    if (self.dataArray.count == 0) {
        [self.conditionLock wait];
    }
    [self.dataArray removeLastObject];
    NSLog(@"删除了元素");
    [self.conditionLock signal];
    [self.conditionLock unlock];
}
@end
  • 7、NSConditionLock是对NSCondition的进一步封装,可以设置具体的条件值
#import "NSConditionLockDemo.h"
#import 

@interface NSConditionLockDemo ()
@property (nonatomic, strong) NSConditionLock *conditionLock;
@end

@implementation NSConditionLockDemo

- (instancetype)init{
    if (self = [super init]) {
        self.conditionLock = [[NSConditionLock  alloc] initWithCondition:1];
    }
    return self;
}

- (void)otherTest{
    [[[NSThread alloc] initWithTarget:self selector:@selector(__one) object:nil] start];
    [[[NSThread alloc] initWithTarget:self selector:@selector(__two) object:nil] start];
}

- (void)__one{
    [self.conditionLock lockWhenCondition:1];
    NSLog(@"添加了元素");
    [self.conditionLock unlockWithCondition:2];
}

- (void)__two{
    [self.conditionLock lockWhenCondition:2];
    NSLog(@"删除了元素");
    [self.conditionLock unlock];
}
@end
  • 8、semaphore叫做”信号量”
    信号量的初始值,可以用来控制线程并发访问的最大数量
    信号量的初始值为1,代表同时只允许1条线程访问资源,保证线程同步
#import "SemaphoreDemo.h"

@interface SemaphoreDemo ()
@property (nonatomic, strong) dispatch_semaphore_t  semaphore;
@end

@implementation SemaphoreDemo

- (instancetype)init{
    if (self = [super init]) {
        self.semaphore = dispatch_semaphore_create(2);
    }
    return self;
}

- (void)otherTest{
    for (int i=0; i<20; i++) {
        [[[NSThread alloc] initWithTarget:self selector:@selector(test) object:nil] start];
    }
}

- (void)test{
    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
    sleep(2);
    NSLog(@"%@",[NSThread currentThread]);
    dispatch_semaphore_signal(self.semaphore);
}
@end
  • 9、直接使用GCD的串行队列,也是可以实现线程同步的
#import "SerialQueueDemo.h"
#import 

@interface SerialQueueDemo ()
@property (nonatomic, strong) dispatch_queue_t ticketQueue;
@property (nonatomic, strong) dispatch_queue_t moneyQueue;
@end

@implementation SerialQueueDemo

- (instancetype)init{
    if (self = [super init]) {
        self.ticketQueue = dispatch_queue_create("ticketQueue", DISPATCH_QUEUE_SERIAL);
        self.moneyQueue = dispatch_queue_create("moneyQueue", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

- (void)__saveMoney{
    dispatch_sync(self.ticketQueue, ^{
        [super __saveMoney];
    });
}

- (void)__drawMoney{
    dispatch_sync(self.ticketQueue, ^{
        [super __drawMoney];
    });
}

- (void)__saleTicket{
    dispatch_sync(self.ticketQueue, ^{
        [super __saleTicket];
    });
}
@end
  • 10、@synchronized是对mutex递归锁的封装
    源码查看:objc4中的objc-sync.mm文件
    @synchronized(obj)内部会生成obj对应的递归锁,然后进行加锁、解锁操作
#import "SynchronizedDemo.h"

@implementation SynchronizedDemo
- (void)__saveMoney{
    @synchronized (self) {        
        [super __saveMoney];
    }
}

- (void)__drawMoney{
    @synchronized (self) {
        [super __drawMoney];
    }
}

- (void)__saleTicket{
    @synchronized (self) {
        [super __saleTicket];
    }
}
@end
  • 11、pthread_rwlock:读写锁
    等待锁的线程会进入休眠
    ✔️ dispatch_barrier_async:异步栅栏调用
    这个函数传入的并发队列必须是自己通过dispatch_queue_cretate创建的
    如果传入的是一个串行或是一个全局的并发队列,那这个函数便等同于
    dispatch_async函数的效果

  • atomic用于保证属性setter、getter的原子性操作,相当于在getter和setter内部加了线程同步的锁
    可以参考源码objc4的objc-accessors.mm
    它并不能保证使用属性的过程是线程安全的

Demo地址

你可能感兴趣的:(多线程-锁)