iOS常见的多线程方案
GCD源码:https://github.com/apple/swift-corelibs-libdispatch
死锁
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"1");
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_sync(queue, ^{
NSLog(@"2");
});
NSLog(@"3");
}
当前队列需要等待viewDidLoad
执行完,才能执行block
里面的内容,而viewDidLoad
又需要等待block
执行完.双方都在等待对方完成,而造成的死锁.
另一个死锁
- (void)interView02
{
NSLog(@"执行任务1");
dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"执行任务2");
dispatch_sync(queue, ^{
NSLog(@"执行任务3");
});
NSLog(@"执行任务4");
});
NSLog(@"执行任务5");
}
网上一道面试题
- (void)test
{
NSLog(@"3");
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
dispatch_queue_t queque = dispatch_get_global_queue(0, 0);
dispatch_async(queque, ^{
NSLog(@"1");
[self performSelector:@selector(test) withObject:nil
afterDelay:0];
NSLog(@"2");
[[NSRunLoop currentRunLoop]addPort:[NSPort new] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
});
}
[self performSelector:@selector(test) withObject:nil afterDelay:0];
的本质是往runloop中添加定时器,子线程默认没有开启runloop.
GNUStep
是GNU计划的项目之一,它将cocoa的oc库开源实现了一遍,非常接近苹果的源码.
源码地址:http://www.gnustep.org/resources/downloads.php 这里可以看到runloop的相关实现
多线程的隐患
当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题
eg.存钱取钱问题.
@interface ViewController ()
@property (nonatomic,assign) int moeny;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.moeny = 100;
// Do any additional setup after loading the view.
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self saveMoeny];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self drawMoney];
}
});
}
//取钱
- (void)drawMoney
{
int oldMoeny = self.moeny;
sleep(0.2);
oldMoeny = oldMoeny - 20;
self.moeny = oldMoeny;
NSLog(@"取20, 还剩%d--%@",oldMoeny,[NSThread currentThread]);
}
//存钱
- (void)saveMoeny
{
int newMoney = self.moeny;
sleep(.2);
newMoney = newMoney + 50;
self.moeny = newMoney;
NSLog(@"存50, 还剩%d--%@",newMoney,[NSThread currentThread]);
}
线程同步技术
OSSpinLock
os_unfair_lock
pthread_mutex
dispatch_semaphore
dispatch_queue(DISPATCH_QUEUE_SERIAL)
NSLock
NSRecursiveLock
NSCondition
NSConditionLock
@synchronized
OSSpinLock
- OSSpinLock叫做”自旋锁”,等待锁的线程会处于忙等(busy-wait)状态,一直占用着CPU资源
- 目前已经不再安全,可能会出现优先级反转问题
- 如果等待锁的线程优先级较高,它会一直占用着CPU资源,优先级低的线程就无法释放锁
#import
//取钱
- (void)drawMoney
{
OSSpinLockLock(&_lock);
int oldMoeny = self.moeny;
sleep(0.2);
oldMoeny = oldMoeny - 20;
self.moeny = oldMoeny;
NSLog(@"取20, 还剩%d--%@",oldMoeny,[NSThread currentThread]);
OSSpinLockUnlock(&_lock);
}
//存钱
- (void)saveMoeny
{
OSSpinLockLock(&_lock);
int newMoney = self.moeny;
sleep(.2);
newMoney = newMoney + 50;
self.moeny = newMoney;
NSLog(@"存50, 还剩%d--%@",newMoney,[NSThread currentThread]);
OSSpinLockUnlock(&_lock);
}
新建基类lockDemo,以后每个种类的lock继承于它便于演示.
@interface lockDemo : NSObject
- (void)drawAndSaveMoneyTest;
- (void)ticketTest;
- (void)drawMoney;
- (void)saveMoeny;
- (void)saleTicket;
@end
@interface lockDemo ()
@property (nonatomic,assign) int moeny;
@property (nonatomic,assign) int ticketsCount;
@end
@implementation lockDemo
- (void)drawAndSaveMoneyTest
{
self.moeny = 100;
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self saveMoeny];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 10; i++) {
[self drawMoney];
}
});
}
//取钱
- (void)drawMoney
{
int oldMoeny = self.moeny;
sleep(0.2);
oldMoeny = oldMoeny - 20;
self.moeny = oldMoeny;
NSLog(@"取20, 还剩%d--%@",oldMoeny,[NSThread currentThread]);
}
//存钱
- (void)saveMoeny
{
int newMoney = self.moeny;
sleep(.2);
newMoney = newMoney + 50;
self.moeny = newMoney;
NSLog(@"存50, 还剩%d--%@",newMoney,[NSThread currentThread]);
}
- (void)saleTicket{
int oldTicketsCount = self.ticketsCount;
sleep(.2);
oldTicketsCount--;
self.ticketsCount = oldTicketsCount;
NSLog(@"还剩%d张票 - %@", oldTicketsCount, [NSThread currentThread]);
}
/**
卖票演示
*/
- (void)ticketTest
{
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];
}
});
}
@end
os_unfair_lock
- os_unfair_lock用于取代不安全的OSSpinLock ,从iOS10开始才支持
- 从底层调用看,等待os_unfair_lock锁的线程会处于休眠状态,并非忙等
- 需要导入头文件#import
@interface os_unfair_locDemo()
@property (nonatomic,assign) os_unfair_lock moneyLock;
@property (nonatomic,assign) os_unfair_lock ticketLock;
@end
@implementation os_unfair_locDemo
- (instancetype)init
{
self = [super init];
if (self) {
self.moneyLock = OS_UNFAIR_LOCK_INIT;
self.ticketLock = OS_UNFAIR_LOCK_INIT;
}
return self;
}
- (void)saleTicket
{
os_unfair_lock_lock(&_ticketLock);
[super saleTicket];
os_unfair_lock_unlock(&_ticketLock);
}
- (void)saveMoeny
{
os_unfair_lock_lock(&_moneyLock);
[super saveMoeny];
os_unfair_lock_unlock(&_moneyLock);
}
- (void)drawMoney
{
os_unfair_lock_lock(&_moneyLock);
[super drawMoney];
os_unfair_lock_unlock(&_moneyLock);
}
@end
pthread_mutex
- mutex叫做”互斥锁”,等待锁的线程会处于休眠状态
- 需要导入头文件#import
@interface mutexDemo()
@property (nonatomic,assign) pthread_mutex_t moneyMutex;
@property (nonatomic,assign) pthread_mutex_t ticketMutex;
@end
@implementation mutexDemo
- (instancetype)init
{
self = [super init];
if (self) {
[self __initMutex:&_moneyMutex];
[self __initMutex:&_ticketMutex];
}
return self;
}
//这里必须要传指针 否则传进来都是同一个pthread_mutex_t
- (void)__initMutex:(pthread_mutex_t *)mutex
{
//定义属性
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(mutex, &attr);
//销毁属性
pthread_mutexattr_destroy(&attr);
}
- (void)saleTicket
{
pthread_mutex_lock(&_ticketMutex);
[super saleTicket];
pthread_mutex_unlock(&_ticketMutex);
}
- (void)saveMoeny
{
pthread_mutex_lock(&_moneyMutex);
[super saveMoeny];
pthread_mutex_unlock(&_moneyMutex);
}
- (void)drawMoney
{
pthread_mutex_lock(&_moneyMutex);
[super drawMoney];
pthread_mutex_unlock(&_moneyMutex);
}
- (void)dealloc
{
pthread_mutex_destroy(&_moneyMutex);
pthread_mutex_destroy(&_ticketMutex);
}
@end
递归锁
- (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_unlock(&_mutex);
}
NS的锁基本上是上述锁的封装.
dispatch_semaphore_t
- semaphore叫做”信号量”
- 信号量的初始值,可以用来控制线程并发访问的最大数量
- 信号量的初始值为1,代表同时只允许1条线程访问资源,保证线程同步
@interface semaphore()
@property (nonatomic,strong) dispatch_semaphore_t semaphore;
@end
@implementation semaphore
- (instancetype)init
{
self = [super init];
if (self) {
self.semaphore = dispatch_semaphore_create(5);
}
return self;
}
- (void)otherTest
{
for (int i = 0; i<100; i++) {
[[[NSThread alloc]initWithTarget:self selector:@selector(test) object:nil] start];
}
}
- (void)test
{
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
sleep(2);
NSLog(@"12345");
dispatch_semaphore_signal(self.semaphore);
}
@end
synchronized
- @synchronized是对mutex递归锁的封装
- 源码查看:objc4中的objc-sync.mm文件
- @synchronized(obj)内部会生成obj对应的递归锁,然后进行加锁、解锁操作
什么情况使用自旋锁比较划算?
- 预计线程等待锁的时间很短
- 加锁的代码(临界区)经常被调用,但竞争情况很少发生
- CPU资源不紧张
- 多核处理器
什么情况使用互斥锁比较划算?
- 预计线程等待锁的时间较长
- 单核处理器
- 临界区有IO操作
- 临界区代码复杂或者循环量大
- 临界区竞争非常激烈