iOS GCD开发运用场景

(一)、线程的概念和与生命周期

进程:可以简单理解为进程为一个应用程序

线程:是CPU调度和分派的基本单位

下图是线程状态示意图,从图中可以看出线程的生命周期是:新建 - 就绪 - 运行 - 阻塞 - 死亡


线程的状态与生命周期.png

(二)、多线程的四种解决方案

多线程的四种解决方案分别是:OC主要使用NSThread,GCD, NSOperation,pthread为跨平台的。


多线程的四种解决方案.png

(三)、GCD的特点和运用场景

GCD是苹果提供的,底层为C 语言写的,一套多线程API ,它具有操作简单、执行高效特点。GCD以block为基本单位,一个block中的代码可以视为一个任务。GCD中有两大最重要的概念,分别是“队列”和“执行方式”。开发者要做的只是定义执行的任务并追加到适当的 Dispatch Queue 中。

(1)GCD术语解释

术语解释.png

(2)GCD几种队列获取方式

  • 主线程队列(The main queue):通过dispatch_get_main_queue()来获得,这是一个串行队列。提交至main queue的任务会在主线程中执行,app中的main函数默认在主线程执行,和UI相关的修改必须使用Main Queue。
  • 全局并发队列(Global queue): 通过调用dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)函数来获取(可以设置优先级),全局并发队列由整个进程共享,有高、中(默认)、低、后台四个优先级别。
  • 自定义队列(Custom queue):通过调用dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)来创建,DISPATCH_QUEUE_CONCURRENT并行队列,可以并发的执行多个任务,但是执行完成的顺序是随机的。DISPATCH_QUEUE_SERIAL串行队列,队列里的任务都是串行执行的,一个执行完再执行下一个。

  • Group queue (队列组):通过调用dispatch_group_create()来获取将多线程进行分组,最大的好处是可获知所有线程的完成情况。 通过 dispatch_group_notify可以直接监听组里所有线程完成情况。

(3)GCD队列异步dispatch_async、同步dispatch_sync执行方式区别

CGCD队列同步异步执行区别.png

(3.1)GCD常用场景一:实现多个异步线程同步操作

我们也知道异步函数 + 串行队列实现任务同步执行更加简单。
不过异步函数 + 串行队列的弊端也是非常明显的:
因为是异步函数,所以系统会开启新(子)线程,又因为是串行队列,所以系统只会开启一个子线程。
这就导致了所有的任务都是在这个子线程中同步的一个一个执行。丧失了并发执行的可能性。
虽然可以完成任务,但是却没有充分发挥CPU多核(多线程)的优势。

/*
 *   同步和异步决定了是否开启新线程(或者说是否具有开启新线程的能力),
 *  串行和并发决定了任务的执行方式——串行执行还是并发执行(或者说开启多少条新线程)
 */
- (void)dispatchAsyncForSerial {
    dispatch_queue_t serialQueue = dispatch_queue_create("dispatchAsyncForSerial", DISPATCH_QUEUE_SERIAL);
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:12];
    for (int i = 0; i < 12; i++) {
        dispatch_async(serialQueue, ^{
            [arrayM addObject:[NSNumber numberWithInt:i]];
            NSLog(@"currentThread = %@, %@",[NSThread currentThread],[NSNumber numberWithInt:i]);
        });
    }
}

输出:nunber = 5 说明开启了一个新线程在执行

currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 0
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 1
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 2
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 3
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 4
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 5
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 6
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 7
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 8
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 9
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 10
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 11
  • Dispatch Semaphore 信号量:

1: 用GCD的信号量来实现异步线程同步操作
2: 保证线程安全,为线程加锁

/*
 *1.dispatch_semaphore_create:创建一个Semaphore并初始化信号的总量
 
 * 2.dispatch_semaphore_signal:发送一个信号,让信号总量加1
 
 * 3.dispatch_semaphore_wait:可以使总信号量减1,当信号总量为0时就会一直等待(阻塞所在线程),否则就可以正常执行。
 */
//MARK: - 用GCD的信号量来实现异步线程同步操作 1:同步且并发执行发挥多核优势 2:保证线程安全,为线程加锁
- (void)dispatchSemaphore {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:12];
    // 创建为1的信号量
    dispatch_semaphore_t sem = dispatch_semaphore_create(1);
    for (int i = 0; i < 12; i++) {
        dispatch_async(queue, ^{
            // 等待信号量
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            [arrayM addObject:[NSNumber numberWithInt:i]];
            NSLog(@"currentThread = %@, %@",[NSThread currentThread],[NSNumber numberWithInt:i]);
            // 发送信号量
            dispatch_semaphore_signal(sem);
        });
    }
}

输出:在多个线程下并发执行完任务

 currentThread = <NSThread: 0x600002db7280>{number = 5, name = (null)}, 0
 currentThread = <NSThread: 0x600002df9480>{number = 6, name = (null)}, 2
 currentThread = <NSThread: 0x600002dfa940>{number = 7, name = (null)}, 1
 currentThread = <NSThread: 0x600002da3180>{number = 8, name = (null)}, 3
 currentThread = <NSThread: 0x600002dc95c0>{number = 4, name = (null)}, 4
 currentThread = <NSThread: 0x600002db8280>{number = 3, name = (null)}, 5
 currentThread = <NSThread: 0x600002df9500>{number = 9, name = (null)}, 6
 currentThread = <NSThread: 0x600002dfa7c0>{number = 10, name = (null)}, 7
 currentThread = <NSThread: 0x600002db7280>{number = 5, name = (null)}, 9
 currentThread = <NSThread: 0x600002da37c0>{number = 11, name = (null)}, 8
 currentThread = <NSThread: 0x600002da4f40>{number = 12, name = (null)}, 10
 currentThread = <NSThread: 0x600002da5080>{number = 13, name = (null)}, 11

(3.2)GCD常用场景二:dispatch_barrier_sync实现多读单写

dispatch_barrier_sync.jpeg
/* 实现多读单写
 * 这里的dispatch_barrier_sync上的队列要和需要阻塞的任务在同一队列上,否则是无效的。
 * 栅栏函数任务:在他之前所有的任务执行完毕,并且在它后面的任务开始之前,期间不会有其他的任务执行,这样比较好的促使 写操作一个接一个写 (写写互斥),不会乱!
 * 运用对NSMutableArray 多读单写保证线程安全
 */

//MARK: - 实现多读单写
-(void)dispatchBarrier {
    
    [self setObject:@"hello kitty" forKey:@"message" waitTime:4];
    for (NSInteger i = 0; i < 10; i++) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self valueForKey:@"message"];
        });
    }
    NSLog(@"写操作hello kitty后的任务");
    [self setObject:@"hello jack" forKey:@"message" waitTime:2];
    for (NSInteger i = 0; i < 10; i++) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self valueForKey:@"message"];
        });
    }
    NSLog(@"写操作hello jack后的任务");
    
    
    [self setObject:@"hello weilian" forKey:@"message" waitTime:3];
    for (NSInteger i = 0; i < 10; i++) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self valueForKey:@"message"];
        });
    }
    NSLog(@"写操作hello weilian后的任务");

}
- (id)valueForKey:(NSString *)key {
    id __block obj;
    // 在调用此函数的线程同步执行所有添加到 queue 队列的读任务,
    // 如果前边有写的任务, 由于 barrier 堵塞队列, 只能等待写任务完成
    dispatch_sync(_dictQueue, ^{
        obj = [self.dict valueForKey:key];
        NSLog(@"read thread = %@, %@",[NSThread currentThread],obj);
    });
    return obj;
}

- (void)setObject:(id)obj forKey:(id<NSCopying>)key waitTime:(int)sleepNum {
    // 重点:dispatch_barrier_async(),异步栅栏调用;栅栏函数堵塞的是队列,添加到队列中的写操作任务, 只能依次按照添加顺序进行修改,不会出现资源抢夺现象
    // 在子线程完成写任务,因为顺序执行只需要开辟一个线程
    // 等待前面任务执行完成后开始写
    // 写的完成任务后, 才能继续执行后边添加进此队列的任务
    dispatch_barrier_async(_dictQueue, ^{
        sleep(sleepNum); //模拟耗时操作
        [self.dict setObject:obj forKey:key];
        NSLog(@"write thread = %@, %@",[NSThread currentThread],obj);
    });
}

输出:

  • 先打印初nslog 的日志,dispatch_barrier_async使用并发且不堵塞当前线程(当前主线程),
  • 我们可以看到 三个写操作虽然他们耗时不同,但都按照入队的顺序依次执行,hello kitty-> hello jack-> hello weilian
  • 后面打印20来个 hello weilian 是因为 在读的过程中有插入写的任务,只有等 dispatch_barrier_async()执行完才能执行后边添加进此队列读任务
写操作hello kitty后的任务
写操作hello jack后的任务
写操作hello weilian后的任务
write thread = <NSThread: 0x600000ea2600>{number = 5, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec6580>{number = 2, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec74c0>{number = 7, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec1000>{number = 3, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ee4ac0>{number = 9, name = (null)}, hello kitty
read thread = <NSThread: 0x600000edc5c0>{number = 10, name = (null)}, hello kitty
write thread = <NSThread: 0x600000edc5c0>{number = 10, name = (null)}, hello jack
read thread = <NSThread: 0x600000ed7980>{number = 11, name = (null)}, hello jack
read thread = <NSThread: 0x600000ee0040>{number = 12, name = (null)}, hello jack
read thread = <NSThread: 0x600000ed5300>{number = 13, name = (null)}, hello jack
write thread = <NSThread: 0x600000ee0040>{number = 12, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0140>{number = 14, name = (null)}, hello weilian
read thread = <NSThread: 0x600000edd340>{number = 17, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2540>{number = 16, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee02c0>{number = 15, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee00c0>{number = 18, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed25c0>{number = 20, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede000>{number = 21, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4680>{number = 19, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4980>{number = 23, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2640>{number = 24, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0240>{number = 22, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2680>{number = 27, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede100>{number = 25, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0300>{number = 26, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2700>{number = 29, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee46c0>{number = 28, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4740>{number = 31, name = (null)}, hello weilian
read thread = <NSThread: 0x600000edc600>{number = 30, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee47c0>{number = 32, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede1c0>{number = 33, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede140>{number = 35, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0340>{number = 34, name = (null)}, hello weilian

(3.3)GCD常用场景三:dispatch_group实现多个网络请求的同步问题


/**dispatch_group 可以实现监听一组任务是否完成,完成后得到通知执行其他的操作
 * dispatch_group_enter标志着一个任务追加到 group,执行一次,相当于 group 中未执行完毕任务数+1
 * dispatch_group_leave标志着一个任务离开了 group,执行一次,相当于 group 中未执行完毕任务数-1。
 * 用dispatch_async(queue, ^{})则必须配合enter和level才能最后执行notify;用dispatch_group_async来提交任务如果是异步的,也必须配合enter和level,
 * 当 group 中未执行完毕任务数为0的时候,才会使dispatch_group_wait解除阻塞,以及执行追加到dispatch_group_notify中的任务。
 */

- (void)dispatch_group_test {
    NSLog(@"group---begin");
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //A1耗时操作
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(1.5);
        NSLog(@"A1耗时操作---%@",[NSThread currentThread]);
        dispatch_group_leave(group);
    });
    
    //A2耗时操作
    dispatch_group_async(group, queue, ^{
        sleep(3);
        NSLog(@"A2耗时操作---%@",[NSThread currentThread]);
    });
    
    
    //B网络请求
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        sleep(4);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"B网络请求---%@",[NSThread currentThread]);
            dispatch_group_leave(group);
        });
    });
    
    
    //C网络请求
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        sleep(2);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"C网络请求---%@",[NSThread currentThread]);
            dispatch_group_leave(group);
        });
        
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        //等前面的异步操作都执行完毕后,回到主线程.
        //模拟耗时操作
        sleep(1);
        //打印当前线程
        NSLog(@"group---end---%@",[NSThread currentThread]);
    });
    NSLog(@"code end");
}

输出:

group---begin
code end
A1耗时操作---<NSThread: 0x60000293dc40>{number = 5, name = (null)}
C网络请求---<NSThread: 0x600002934740>{number = 1, name = main}
A2耗时操作---<NSThread: 0x60000297e9c0>{number = 6, name = (null)}
B网络请求---<NSThread: 0x600002934740>{number = 1, name = main}
group---end---<NSThread: 0x600002934740>{number = 1, name = main}

总结:

  • dispatch_group是一个初始值为LONG_MAX的信号量,group中的任务完成是判断其value是否恢复成初始值。
  • dispatch_group_enter和dispatch_group_leave必须成对使用并且支持嵌套。
  • 如果dispatch_group_enter比dispatch_group_leave多,由于value不等于dsema_orig不会走到唤醒逻辑,dispatch_group_notify中的任务无法执行或者dispatch_group_wait收不到信号而卡住线程。
  • 如果是dispatch_group_leave多,则会引起崩溃。

(3.4)GCD造成主线死锁的情况

/*
 * 1、主队列同步任务,造成相互等待,死锁
 * 2、串行队列(同步/异步任务)嵌套同步任务,造成相互等待,死锁
 */
- (void)deathLock {
    //1、主队列同步任务,造成相互等待,死锁
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"deallock");
    });
    
    //2、串行队列(同步/异步任务)嵌套同步任务,造成相互等待,死锁
    dispatch_queue_t serialQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
    dispatch_async(serialQueue, ^{
        dispatch_sync(serialQueue, ^{
            NSLog(@"deadlock");
        });
    });
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容