多线程-锁

2018-11-25  本文已影响0人  朝夕向背

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

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

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

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

#import "OSSpinLockDemo.h"
#import <libkern/OSAtomic.h>

@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

#import "OSUnfairLockDemo.h"
#import <libkern/OSAtomic.h>
#import <os/lock.h>

@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
#import "MutexDemo.h"
#import <pthread.h>

@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
#import "NSLockDemo.h"
#import <pthread.h>

@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
#import "NSConditionDemo.h"
#import <pthread.h>

@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
#import "NSConditionLockDemo.h"
#import <pthread.h>

@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
#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
#import "SerialQueueDemo.h"
#import <pthread.h>

@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
#import "SynchronizedDemo.h"

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

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

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

Demo地址

上一篇 下一篇

猜你喜欢

热点阅读