资源共享
1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源
比如多个线程访问同一个对象、同一个变量、同一个文件
当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
一.错误示例
1.1 卖票未使用线程锁之前的问题
示例图.png- (void)viewDidLoad {
[super viewDidLoad];
[self saleTickets];
}
-(void)saleTicket {
int oldTicketsCount = self.ticketsCount;
// sleep(.2); //如果休眠一会,会更加明显
oldTicketsCount --;
self.ticketsCount = oldTicketsCount;
NSLog(@"还剩%d张票 - %@",oldTicketsCount,[NSThread currentThread]);
}
-(void)saleTickets {
self.ticketsCount = 15;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i<5; i++) {
[self saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i<5; i++) {
[self saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i<5; i++) {
[self saleTicket];
}
});
}
打印结果会出现错误:没有卖完,而且还有结果相等的时候。
image.png
1.2 存取钱未使用线程锁之前的问题
示例图.png- (void)viewDidLoad {
[super viewDidLoad];
[self moneyTest];
}
//存取钱演示
-(void)moneyTest {
self.money = 100;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i<10; i++) {
[self saveMoney];
}
});
dispatch_async(queue, ^{
for (int i = 0; i<10; i++) {
[self drawMoney];
}
});
}
//存钱
-(void)saveMoney {
int oldMoney = self.money;
sleep(.2); //如果休眠一会,会更加明显
oldMoney += 50;
self.money = oldMoney;
NSLog(@"存50,还剩%d元 - %@",oldMoney,[NSThread currentThread]);
}
//取钱
-(void)drawMoney {
int oldMoney = self.money;
sleep(.2); //如果休眠一会,会更加明显
oldMoney -= 20;
self.money = oldMoney;
NSLog(@"取20,还剩%d元 - %@",oldMoney,[NSThread currentThread]);
}
打印结果
image.png
二.iOS中的线程同步方案
OSSpinLock(自旋锁)
os_unfair_lock
pthread_mutex(互斥锁)
dispatch_semaphore (信号量实现加锁)
dispatch_queue(DISPATCH_QUEUE_SERIAL)
NSLock(对象锁)
NSRecursiveLock (递归锁)
NSCondition (条件锁)
NSConditionLock(条件锁)
@synchronized
三.代码示范
3.1 OSSpinLock(该方法已废弃,不推荐使用)
OSSpinLock叫做”自旋锁”,等待锁的线程会处于忙等(busy-wait)状态,一直占用着CPU资源
目前已经不再安全,可能会出现优先级反转问题
如果等待锁的线程优先级较高,它会一直占用着CPU资源,优先级低的线程就无法释放锁
需要导入头文件#import <libkern/OSAtomic.h>
image.png
卖票问题解决方案:
@property (assign, nonatomic) OSSpinLock ticketLock;
self.ticketLock = OS_SPINLOCK_INIT;
- (void)__saleTicket {
OSSpinLockLock(&_ticketLock);
[super __saleTicket];
OSSpinLockUnlock(&_ticketLock);
}
3.2 os_unfair_lock
os_unfair_lock用于取代不安全的OSSpinLock ,从iOS10开始才支持
从底层调用看,等待os_unfair_lock锁的线程会处于休眠状态,并非忙等
需要导入头文件#import <os/lock.h>
image.png
卖票问题解决方案:
@property (assign, nonatomic) os_unfair_lock ticketLock;
self.ticketLock = OS_UNFAIR_LOCK_INIT;
- (void)__saleTicket {
os_unfair_lock_lock(&_ticketLock);
[super __saleTicket];
os_unfair_lock_unlock(&_ticketLock);
}
3.3 pthread_mutex
mutex叫做”互斥锁”,等待锁的线程会处于休眠状态
需要导入头文件#import <pthread.h>
pthread_mutex
.png
pthread_mutex – 递归锁.png
pthread_mutex – 条件 .png
卖票问题解决方案:
@property (assign, nonatomic) pthread_mutex_t ticketMutex;
- (void)__initMutex:(pthread_mutex_t *)mutex {
// 初始化锁
pthread_mutex_init(mutex, NULL);
}
[self __initMutex:&_ticketMutex];
- (void)__saleTicket {
pthread_mutex_lock(&_ticketMutex);
[super __saleTicket];
pthread_mutex_unlock(&_ticketMutex);
}
- (void)dealloc {
pthread_mutex_destroy(&_ticketMutex);
}
问题1:这段代码有问题吗?
- (void)otherTest {
pthread_mutex_lock(&_mutex);
NSLog(@"%s", __func__);
[self otherTest2];
pthread_mutex_unlock(&_mutex);
}
- (void)otherTest2 {
pthread_mutex_lock(&_mutex);
NSLog(@"%s", __func__);
pthread_mutex_unlock(&_mutex);
}
- 会造成死锁。可以通过在otherTest2内使用另外一把锁即可解决。
问题2:这段代码有问题吗?
- (void)otherTest {
pthread_mutex_lock(&_mutex);
NSLog(@"%s", __func__);
[self otherTest];
pthread_mutex_unlock(&_mutex);
}
- 也会造成死锁。可以通过一个递归锁解决。方案如下:
- (void)__initMutex:(pthread_mutex_t *)mutex {
// 递归锁:允许同一个线程对一把锁进行重复加锁 PTHREAD_MUTEX_RECURSIVE(递归锁)
// 初始化属性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
// 初始化锁
pthread_mutex_init(mutex, &attr);
// 销毁属性
pthread_mutexattr_destroy(&attr);
}
3.4 NSLock(对象锁),NSRecursiveLock(递归锁)
image.png卖票问题解决方案:
@property (strong, nonatomic) NSLock *ticketLock;
self.ticketLock = [[NSLock alloc] init];
- (void)__saleTicket {
[self.ticketLock lock];
[super __saleTicket];
[self.ticketLock unlock];
}
3.5 NSCondition(对pthread_mutex的mutex和cond的封装)
image.png3.6 NSConditionLock
NSConditionLock是对NSCondition的进一步封装,可以设置具体的条件值
image.png
使用示例:(可以根据条件值进行顺序执行)
@property (strong, nonatomic) NSConditionLock *conditionLock;
self.conditionLock = [[NSConditionLock alloc] initWithCondition:1];
- (void)otherTest {
[[[NSThread alloc] initWithTarget:self selector:@selector(__one) object:nil] start];
[[[NSThread alloc] initWithTarget:self selector:@selector(__two) object:nil] start];
[[[NSThread alloc] initWithTarget:self selector:@selector(__three) object:nil] start];
}
- (void)__one {
[self.conditionLock lock];
NSLog(@"__one");
sleep(1);
[self.conditionLock unlockWithCondition:2];
}
- (void)__two {
[self.conditionLock lockWhenCondition:2];
NSLog(@"__two");
sleep(1);
[self.conditionLock unlockWithCondition:3];
}
- (void)__three {
[self.conditionLock lockWhenCondition:3];
NSLog(@"__three");
[self.conditionLock unlock];
}
3.7 dispatch_queue
直接使用GCD的串行队列,也是可以实现线程同步的
卖票解决方案:
@property (strong, nonatomic) dispatch_queue_t ticketQueue;
self.ticketQueue = dispatch_queue_create("ticketQueue", DISPATCH_QUEUE_SERIAL);
- (void)__saleTicket
{
dispatch_sync(self.ticketQueue, ^{
[super __saleTicket];
});
}
3.8 dispatch_semaphore
semaphore叫做”信号量”
信号量的初始值,可以用来控制线程并发访问的最大数量
信号量的初始值为1,代表同时只允许1条线程访问资源,保证线程同步
image.png
卖票解决方案:
@property (strong, nonatomic) dispatch_semaphore_t ticketSemaphore;
self.ticketSemaphore = dispatch_semaphore_create(1);
- (void)__saleTicket {
dispatch_semaphore_wait(self.ticketSemaphore, DISPATCH_TIME_FOREVER);
[super __saleTicket];
dispatch_semaphore_signal(self.ticketSemaphore);
}
3.9 @synchronized
@synchronized是对mutex递归锁的封装
源码查看:objc4中的objc-sync.mm文件
@synchronized(obj)内部会生成obj对应的递归锁,然后进行加锁、解锁操作
image.png
卖票解决方案:
- (void)__saleTicket {
@synchronized([self class]) {
[super __saleTicket];
}
}
网友评论