Objective-C基础-多线程

2019-08-04  本文已影响0人  学习天亦

1、常见多线程方案

多线程方案.jpg

2、队列与同步异步

队列与同步异步.jpg

例子

@interface ViewController ()

@end

@implementation ViewController


// dispatch_sync和dispatch_async用来控制是否要开启新的线程
/**
 队列的类型,决定了任务的执行方式(并发、串行)
 1.并发队列
 2.串行队列
 3.主队列(也是一个串行队列)
 */

- (void)test01 {
    // 问题:以下代码是在主线程执行的,会不会产生死锁?会!
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue, ^{
        NSLog(@"执行任务2");
    });
    
    NSLog(@"执行任务3");
    
    // dispatch_sync立马在当前线程同步执行任务
}

- (void)test02 {
    // 问题:以下代码是在主线程执行的,会不会产生死锁?不会!
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        NSLog(@"执行任务2");
    });
    NSLog(@"执行任务3");
    
    // dispatch_async不要求立马在当前线程同步执行任务
}

- (void)test03 {
    // 问题:以下代码是在主线程执行的,会不会产生死锁?会!
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_queue_create("myqueu", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{ // 0
        NSLog(@"执行任务2");
        
        dispatch_sync(queue, ^{ // 1
            NSLog(@"执行任务3");
        });
    
        NSLog(@"执行任务4");
    });
    
    NSLog(@"执行任务5");
}

- (void)test04 {
    // 问题:以下代码是在主线程执行的,会不会产生死锁?不会!
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_queue_create("myqueu", DISPATCH_QUEUE_SERIAL);
//    dispatch_queue_t queue2 = dispatch_queue_create("myqueu2", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t queue2 = dispatch_queue_create("myqueu2", DISPATCH_QUEUE_SERIAL);
    
    dispatch_async(queue, ^{ // 0
        NSLog(@"执行任务2");
        
        dispatch_sync(queue2, ^{ // 1
            NSLog(@"执行任务3");
        });
        
        NSLog(@"执行任务4");
    });
    
    NSLog(@"执行任务5");
}

- (void)test05 {
    // 问题:以下代码是在主线程执行的,会不会产生死锁?不会!
    NSLog(@"执行任务1");
    
    dispatch_queue_t queue = dispatch_queue_create("myqueu", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{ // 0
        NSLog(@"执行任务2");
        
        dispatch_sync(queue, ^{ // 1
            NSLog(@"执行任务3");
        });
        
        NSLog(@"执行任务4");
    });
    
    NSLog(@"执行任务5");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self test01];
    [self test02];
    [self test03];
    [self test04];
    [self test05];
}

@end

练习

- (void)viewDidLoad {
    [super viewDidLoad];
    [self test3];
}

- (void)test3 {
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        // 这句代码的本质是往Runloop中添加定时器 Runloop没有启动,所以会输出1、3
        [self performSelector:@selector(test) withObject:nil afterDelay:.0];
        NSLog(@"3");
    });
}

- (void)test {
    NSLog(@"2");
}
//输出 1、3
- (void)viewDidLoad {
    [super viewDidLoad];
    [self test3];
}

- (void)test3 {
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        // 这句代码的本质是往Runloop中添加定时器
        [self performSelector:@selector(test) withObject:nil afterDelay:.0];
        NSLog(@"3");
        //启动Runloop,停在这里, 输出1、3、2 不会输出4
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"4");
    });
}

- (void)test {
    NSLog(@"2");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");
    }];
    [thread start];
    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:NO];
}

- (void)test {
    NSLog(@"2");
}

//输出1,线程执行完任务就停掉了
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"0");
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"1");

    }];
    [thread start];
    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:NO];
}

- (void)test {
    NSLog(@"2");
}
//输出0、2
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"0");
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        NSLog(@"1");

    }];
    [thread start];
    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:NO];
}

- (void)test {
    NSLog(@"2");
}
//输出0、2、1

3、队列组的使用

异步并发执行任务1、任务2
等任务1、任务2都执行完毕后,再回到主线程执行任务3

- (void)test {
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_async(group, queue, ^{
        NSLog(@"任务1");
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"任务2");
    });
    
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"任务3");
        });
    });
}

4、线程同步

iOS中的线程同步方案

4.1 OSSpinLock

OSSpinLock lock = OS_SPINLOCK_INIT;//初始化
//尝试加锁,如果需要等待就不加锁,直接返回false,如果不需要等待就加锁,返回false
bool result = OSSpinLockTry(&lock);
OSSpinLockLock(&lock);//加锁
OSSpinLockUnlock(&lock);//解锁

4.2 os_unfair_lock

os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;//初始化
//尝试加锁,如果需要等待就不加锁,直接返回false,如果不需要等待就加锁,返回false
bool result = os_unfair_lock_trylock(&lock);
os_unfair_lock_lock(&lock);//加锁
os_unfair_lock_unlock(&lock);//加锁

4.3 pthread_mutex

4.3.1 pthread_mutex 互斥锁

// 初始化锁的属性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
    
// 初始化锁
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, &attr);
    
//尝试加锁
pthread_mutex_trylock(&mutex);
//加锁
pthread_mutex_lock(&mutex);
    
//解锁
pthread_mutex_unlock(&mutex);

//销毁相关资源
pthread_mutexattr_destroy(&attr);
pthread_mutex_destroy(&mutex);
/*
 * Mutex type attributes
 */
#define PTHREAD_MUTEX_NORMAL        0
#define PTHREAD_MUTEX_ERRORCHECK    1
#define PTHREAD_MUTEX_RECURSIVE     2
#define PTHREAD_MUTEX_DEFAULT       PTHREAD_MUTEX_NORMAL

4.3.2 pthread_mutex 递归锁

// 初始化锁的属性
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
    
// 初始化锁
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, &attr);

4.3.3 pthread_mutex 条件

可用作生产者-消费者模式

// 初始化锁
pthread_mutex_t mutex;
// NULL代表使用默认属性
pthread_mutex_init(&mutex, NULL);
    
// 初始化条件
pthread_cond_t condition;
pthread_cond_init(&condition, NULL);
    
//等待条件 (进入休眠,放开mutex锁;被唤醒后,会再次对mutex加锁)
pthread_cond_wait(&condition, &mutex);

//激活一个等待该条件的线程
pthread_cond_signal(&condition);
    
//激活所有等待该条件的线程
pthread_cond_broadcast(&condition);
 
//销毁相关资源
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition);

4.4 NSLock、NSRecursiveLock

@interface NSLock : NSObject <NSLocking> {
- (BOOL)tryLock;
- (BOOL)lockBeforeDate:(NSDate *)limit;
@end
@protocol NSLocking
- (void)lock;
- (void)unlock;
@end
//初始化锁
NSLock *lock = [[NSLock alloc] init];

4.5 NSCondition、NSConditionLock

@interface NSCondition : NSObject <NSLocking> {
- (void)wait;
- (BOOL)waitUntilDate:(NSDate *)limit;
- (void)signal;
- (void)broadcast;
@end

@interface NSConditionLock : NSObject <NSLocking> {
- (instancetype)initWithCondition:(NSInteger)condition NS_DESIGNATED_INITIALIZER;
@property (readonly) NSInteger condition;
- (void)lockWhenCondition:(NSInteger)condition;
- (BOOL)tryLock;
- (BOOL)tryLockWhenCondition:(NSInteger)condition;
- (void)unlockWithCondition:(NSInteger)condition;
- (BOOL)lockBeforeDate:(NSDate *)limit;
- (BOOL)lockWhenCondition:(NSInteger)condition beforeDate:(NSDate *)limit;

@end

4.6 dispatch_semaphore

//信号量初始值
int value = 1;
//初始化信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(value);
//如果信号量的值 <=0, 当前线程就会进入休眠等待(直到信号量的值>0)
//如果信号量的值 <=0, 就减1然后往下执行后面的代码
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//让信号量的值加1
dispatch_semaphore_signal(semaphore);

4.7 dispatch_queue

dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
    //任务
});

4.8 @synchronized

@synchronized (obj) {
    //任务
}

4.9 线程同步方案性能比较

性能从高到低排序

4.10 自旋锁、互斥锁比较

什么情况使用自旋锁比较划算?

什么情况使用互斥锁比较划算?

5 atomic

atomic用于保证属性setter、getter的原子性操作,相当于在getter和setter内部加了线程同步的锁

6、iOS中的读写安全方案

上面的场景就是典型的"多读单写",经常用于文件等数据的读写操作,iOS中的实现方案有

6.1 pthread_rwlock

等待锁的线程会进入休眠

//初始化锁
pthread_rwlock_t lock;
pthread_rwlock_init(&lock, NULL);
// 读加锁
pthread_rwlock_rdlock(&lock);
// 读尝试加锁
pthread_rwlock_tryrdlock(&lock);
// 写加锁
pthread_rwlock_wrlock(&lock);
// 写尝试加锁
pthread_rwlock_trywrlock(&lock);

// 解锁
pthread_rwlock_unlock(&lock);
//销毁
pthread_rwlock_destroy(&lock);

6.2 dispatch_barrier_async

dispatch_queue_t queue = dispatch_queue_create("rw_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
   //读
});
    
dispatch_barrier_async(queue, ^{
    //写
});
上一篇下一篇

猜你喜欢

热点阅读