iOS —— 多线程应用

一、共享资源

共享资源 : 就是内存中的一块资源同时被多个进程所访问,而每个进程可能会对该资源的数据进行修改

问题 : 如果 线程A 访问了某块资源 C,并且修改了其中的数据,此时 线程B 也访问了 资源C,并且也对 C 中的数据进行了修改;那么等到 线程A 和 线程B 执行结束后,此时,资源C 中的数据就并不是最初的设置了

 

如图

技术分享

 

此时,如果用户想获取 被 线程A 修改的 资源C 的数据,但是 资源C 的数据也被 线程B 修改了,所以获得的是错误的数据;如果用户想获取 被 线程B 修改的 资源C 的数据,但是 资源C 的数据也被 线程A 修改了,所以获得的是错误的数据

 

下面看代码,以出售火车票为例

建立火车票数据模型

 

 1 // LHTicketModal.h 2 #import <Foundation/Foundation.h> 3  4 @interface LHTicketModal : NSObject 5  6 @property (nonatomic) NSUInteger ticketCount; // 剩余票数 7 @property (nonatomic) NSUInteger ticketSaleCount; // 卖出数量 8  9 @end10 11 // LHTicketModal.m12 #import "LHTicketModal.h"13 14 static const NSUInteger kTicketTotalCount = 50;15 16 @implementation LHTicketModal17 18 - (instancetype)init {19 20 self = [super init];21 22 if (self) {23 24 // 初始化剩余票数应该为总数25 _ticketCount = kTicketTotalCount;26 27 // 初始化卖出票数应该为 028 _ticketSaleCount = 0;29 30  }31 32 return self;33 34 }35 36 @end

 

 

UIViewController 代码

 1 // LHSharedViewController.h 2 #import "LHSharedViewController.h" 3 #import "LHTicketModal.h" 4  5 @interface LHSharedViewController () 6  7 // 车票模型 8 @property (nonatomic, strong) LHTicketModal * ticket; 9 10 // 线程对象11 @property (nonatomic, strong) NSThread * threadBJ;12 @property (nonatomic, strong) NSThread * threadSH;13 14 @end15 16 // LHSharedViewController.m17 @implementation LHSharedViewController18 19 - (void)viewDidLoad {20 21  [super viewDidLoad];22 23 // 1. 初始化 票数模型对象24 _ticket = [[LHTicketModal alloc] init];25 26 // 2. 初始化 线程对象 并设置线程名27 _threadBJ = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets:) object:@"北京卖出"];28 29 _threadBJ.name = @"北京";30 31 _threadSH = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets:) object:@"上海卖出"];32 33 _threadSH.name = @"上海";34 35 }36 37 // 线程执行的方法38 - (void)sellTickets:(NSString *)str {39 40 while (YES) {41 42 // 判断剩余量是否大于 0,大于 0 才可以卖出43 if (_ticket.ticketCount > 0) {44 45 // 暂停一段时间46 [NSThread sleepForTimeInterval:0.2];47 48 // 卖出一张票,剩余票数减 1,卖出票数加 149 _ticket.ticketCount--;50 51 _ticket.ticketSaleCount++;52 53 // 获取当前进程54 NSThread * currentThread = [NSThread currentThread];55 56 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);57 58  }59 60  }61 62 }63 64 // 按钮的动作方法65 - (IBAction)startSaleBtnClick:(id)sender {66 67 // 开启线程68  [_threadBJ start];69 70  [_threadSH start];71 72 73 }

点击按钮后,线程开始运行,结果如图

技术分享

 

看一看出,共享资源同时被多个线程访问并修改,导致用户取得了错误的数据

 

那么解决这种情况的办法就是 加锁

加锁是指对一段代码进行加锁,加锁之后,若一个线程已经在对共享资源的数据修改,此时就不会再有其他线程来访问该资源进行修改,直至当前线程已经结束修改资源的代码时,其他进程才可以对其进行修改

可以把共享资源看做一个房间,线程看做人;当一个人进入房间之后就会锁门(加锁),对房间进行各种布置,此时其他人是进不来的,因为没有钥匙;直至当前的人出房间,其他的人才可以进房间进行布置

 

加锁的方式有多种,这里介绍两种

方式一 : 使用  @synchronized (加锁对象) {} 关键字

只需修改上述代码的  sellTickets 方法,其余不变,这里将其方法名改为  sellTickets_v2

 1 - (void)sellTickets_v2:(NSString *)str { 2  3 while (YES) { 4  5 // 对当前对象加锁 6  @synchronized (self) { 7  8 // 判断剩余量是否大于 0,大于 0 才可以卖出 9 if (_ticket.ticketCount > 0) {10 11 // 暂停一段时间12 [NSThread sleepForTimeInterval:0.2];13 14 // 卖出一张票,剩余票数减 1,卖出票数加 115 _ticket.ticketCount--;16 17 _ticket.ticketSaleCount++;18 19 // 获取当前进程20 NSThread * currentThread = [NSThread currentThread];21 22 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);23 24  }25 26  }27 28  }29 30 }

再次运行程序,点击按钮。结果如图

技术分享

 

 

方式二 : 使用 NSCondition 类

在 类扩展中声明并在 viewDidLoad 方法中初始化

 

 1 - (void)sellTickets_v3:(NSString *)str { 2  3 while (YES) { 4  5 // 使用 NSCondition 加锁 6 [_ticketCondition lock]; 7  8 // 判断剩余量是否大于 0,大于 0 才可以卖出 9 if (_ticket.ticketCount > 0) {10 11 // 暂停一段时间12 [NSThread sleepForTimeInterval:0.2];13 14 // 卖出一张票,剩余票数减 1,卖出票数加 115 _ticket.ticketCount--;16 17 _ticket.ticketSaleCount++;18 19 // 获取当前进程20 NSThread * currentThread = [NSThread currentThread];21 22 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);23 24  }25 26 // 使用 NSCondition 解锁27  [_ticketCondition unlock];28 29  }30 31 }

 

运行结果和上述一样

使用 NSCondition 时,将加锁的代码放在 loac 和 unlock 中间

 

总结 :

  1. 互斥锁的优缺点

    优点 : 有效防止因多线程抢夺资源造成的数据安全问题

    缺点 : 需要消耗大量 CPU 资源

 

  2. 互斥锁使用的前提

    多个线程抢夺同一资源

    线程同步,互斥锁就是使用了线程同步  

 

相关文章