美文网首页
iOS多线程梳理-GCD

iOS多线程梳理-GCD

作者: 孟子幻 | 来源:发表于2017-10-11 17:36 被阅读0次

    GCD简介

    Grand Central Dispatch (GCD)是苹果为多核的并行运算提出的解决方案,所以会自动合理地利用更多的CPU内核,最重要的是它会自动管理线程的生命周期(创建线程、调度任务、销毁线程),完全不需要我们管理。

    任务

    即操作,你想要干什么,就是一段代码,在 GCD 中就是一个 Block。任务有两种执行方式: 同步执行和异步执行

    • 同步(sync)执行

    它会阻塞当前线程并等待block中的任务执行完毕,然后当前线程才会继续往下执行

    • 异步(async)执行

    当前线程会直接往下执行,不会阻塞当前线程

    异步和同步的主要区别在于会不会造成阻塞,直到block中的任务执行完毕

    队列

    用于存放任务。一共有两种队列,串行队列 和 并发队列。

    • 串行(serial)队列

    放到串行队列的任务,GCD 会 FIFO(先进先出) 地取出来一个,执行一个,然后取下一个,这样一个一个的执行(只有一个线程)

    • 并发(concurrent)队列

    放到并发队列的任务,GCD 也会 FIFO取出来,但不同的是,它取出来一个就会放到线程中,然后再取出来一个又放到线程中,不必等待已经启动的任务完成。这样由于取的动作很快,忽略不计,看起来,所有的任务都是一起执行的。不过需要注意,GCD 会根据系统资源控制并发的数量,所以如果任务很多,它并不会让所有任务同时执行

    不管是并发队列还是串行队列,任务总是以先进先出的顺序执行。

    • 创建自定义队列

    使用dispatch_queue_create来创建队列,需要传入两个参数,第一个参数表示队列的唯一标识符,用于DEBUG,可为空;第二个参数用来识别是串行队列还是并发队列。DISPATCH_QUEUE_SERIAL或 NULL表示串行队列,DISPATCH_QUEUE_CONCURRENT表示并发队列。

    队列和任务组合探索

    • 主队列+同步
        //主队列是特殊的串行队列
        dispatch_queue_t serialMQ = dispatch_get_main_queue();
        dispatch_sync(serialMQ, ^{
            NSLog(@"T %@",[NSThread currentThread]);
        });
    /*输出结果:
     出现死锁
    */
    

    造成死锁的原因是在同一串行队列执行同步任务。下一篇会对GCD死锁进行梳理

    • 串行队列+同步
    -(void)syncSerialTest{
        NSLog(@"beagin %@",[NSThread currentThread]);
        dispatch_queue_t serialQ = dispatch_queue_create("flag", DISPATCH_QUEUE_SERIAL);
        dispatch_sync(serialQ, ^{
            sleep(2);
            NSLog(@"first %@",[NSThread currentThread]);
        });
        dispatch_sync(serialQ, ^{
            sleep(3);
            NSLog(@"section %@",[NSThread currentThread]);
        });
        dispatch_sync(serialQ, ^{
            sleep(2);
            NSLog(@"three %@",[NSThread currentThread]);
        });
        NSLog(@"end %@",[NSThread currentThread]);
    }
    /*输出结果:
     2017-10-10 21:52:05.025040+0800 GCDLearnAdvanced[8223:1589580] beagin <NSThread: 0x60400006f700>{number = 1, name = main}
     2017-10-10 21:52:07.026478+0800 GCDLearnAdvanced[8223:1589580] first <NSThread: 0x60400006f700>{number = 1, name = main}
     2017-10-10 21:52:10.027137+0800 GCDLearnAdvanced[8223:1589580] section <NSThread: 0x60400006f700>{number = 1, name = main}
     2017-10-10 21:52:12.028410+0800 GCDLearnAdvanced[8223:1589580] three <NSThread: 0x60400006f700>{number = 1, name = main}
     2017-10-10 21:52:12.028716+0800 GCDLearnAdvanced[8223:1589580] end <NSThread: 0x60400006f700>{number = 1, name = main}
     */
    

    所有任务都是在主线程中执行的,并没有开启新的线程。因为串行队列,所以按顺序一个一个执行
    所有任务打印在begin和end之间,说明任务是添加到队列中马上执行的

    • (全局) 并发队列+同步
    -(void)syncConcurrentTest{
        NSLog(@"beagin %@",[NSThread currentThread]);
        dispatch_queue_t concurrentQ = dispatch_queue_create("flag", DISPATCH_QUEUE_CONCURRENT);
        //dispatch_queue_t concurrentQ = dispatch_get_global_queue(0, 0);
        dispatch_sync(concurrentQ, ^{
            sleep(2);
            NSLog(@"first %@",[NSThread currentThread]);
        });
        dispatch_sync(concurrentQ, ^{
            sleep(3);
            NSLog(@"section %@",[NSThread currentThread]);
        });
        dispatch_sync(concurrentQ, ^{
            sleep(2);
            NSLog(@"three %@",[NSThread currentThread]);
        });
        NSLog(@"end %@",[NSThread currentThread]);
    } 
    /*输出结果:
     2017-10-10 21:48:09.785219+0800 GCDLearnAdvanced[8093:1584273] beagin <NSThread: 0x60400007fb00>{number = 1, name = main}
     2017-10-10 21:48:11.786619+0800 GCDLearnAdvanced[8093:1584273] first <NSThread: 0x60400007fb00>{number = 1, name = main}
     2017-10-10 21:48:14.787145+0800 GCDLearnAdvanced[8093:1584273] section <NSThread: 0x60400007fb00>{number = 1, name = main}
     2017-10-10 21:48:16.787967+0800 GCDLearnAdvanced[8093:1584273] three <NSThread: 0x60400007fb00>{number = 1, name = main}
     2017-10-10 21:48:16.788215+0800 GCDLearnAdvanced[8093:1584273] end <NSThread: 0x60400007fb00>{number = 1, name = main}
     */
    

    所有任务都是在主线程中执行。共计耗时7s
    所有任务打印在begin和end之间,说明任务是添加到队列中马上执行的

    • 主队列+异步
    -(void)asyncMainTest{
        NSLog(@"beagin %@",[NSThread currentThread]);
        dispatch_queue_t serialQ = dispatch_get_main_queue();
        dispatch_async(serialQ, ^{
            sleep(2);
            NSLog(@"first %@",[NSThread currentThread]);
        });
        dispatch_async(serialQ, ^{
            sleep(3);
            NSLog(@"section %@",[NSThread currentThread]);
        });
        dispatch_async(serialQ, ^{
            sleep(2);
            NSLog(@"three %@",[NSThread currentThread]);
        });
        NSLog(@"end %@",[NSThread currentThread]);
    }
    /*输出结果:
     2017-10-10 21:57:20.815390+0800 GCDLearnAdvanced[8393:1597214] beagin <NSThread: 0x6040000770c0>{number = 1, name = main}
     2017-10-10 21:57:20.815672+0800 GCDLearnAdvanced[8393:1597214] end <NSThread: 0x6040000770c0>{number = 1, name = main}
     2017-10-10 21:57:22.843484+0800 GCDLearnAdvanced[8393:1597214] first <NSThread: 0x6040000770c0>{number = 1, name = main}
     2017-10-10 21:57:25.844825+0800 GCDLearnAdvanced[8393:1597214] section <NSThread: 0x6040000770c0>{number = 1, name = main}
     2017-10-10 21:57:27.845596+0800 GCDLearnAdvanced[8393:1597214] three <NSThread: 0x6040000770c0>{number = 1, name = main}
     */
    

    所有任务都在主线程中,虽然是异步执行,具备开启线程的能力,但因为是主队列,所以所有任务都在主线程中,并且一个接一个执行。
    任务打印在begin和end之后,说明任务不是马上执行,而是将所有任务添加到队列之后才开始同步执行。

    • 串行队列+异步
    -(void)asyncSerialTest{
        NSLog(@"beagin %@",[NSThread currentThread]);
        dispatch_queue_t serialQ = dispatch_queue_create("flag", DISPATCH_QUEUE_SERIAL);
        dispatch_async(serialQ, ^{
            sleep(2);
            NSLog(@"first %@",[NSThread currentThread]);
        });
        dispatch_async(serialQ, ^{
            sleep(3);
            NSLog(@"section %@",[NSThread currentThread]);
        });
        dispatch_async(serialQ, ^{
            sleep(2);
            NSLog(@"three %@",[NSThread currentThread]);
        });
        NSLog(@"end %@",[NSThread currentThread]);
    }
    /*输出结果:
     2017-10-10 21:53:36.632945+0800 GCDLearnAdvanced[8298:1591682] beagin <NSThread: 0x60000006da40>{number = 1, name = main}
     2017-10-10 21:53:36.633163+0800 GCDLearnAdvanced[8298:1591682] end <NSThread: 0x60000006da40>{number = 1, name = main}
     2017-10-10 21:53:38.636117+0800 GCDLearnAdvanced[8298:1591729] first <NSThread: 0x600000269b80>{number = 3, name = (null)}
     2017-10-10 21:53:41.641004+0800 GCDLearnAdvanced[8298:1591729] section <NSThread: 0x600000269b80>{number = 3, name = (null)}
     2017-10-10 21:53:43.646228+0800 GCDLearnAdvanced[8298:1591729] three <NSThread: 0x600000269b80>{number = 3, name = (null)}
     */
    

    开启了一条新线程,但是任务还是串行,所以任务是一个一个执行。共耗时7s
    任务打印在begin和end之后,说明任务不是马上执行,而是将所有任务添加到队列之后才开始同步执行。

    • (全局)并发队列+异步
    -(void)asyncConcurrentTest{
        NSLog(@"beagin %@",[NSThread currentThread]);
        dispatch_queue_t concurrentQ = dispatch_queue_create("flag", DISPATCH_QUEUE_CONCURRENT);
        //dispatch_queue_t concurrentQ = dispatch_get_global_queue(0, 0);
        dispatch_async(concurrentQ, ^{
            sleep(2);
            NSLog(@"first %@",[NSThread currentThread]);
        });
        dispatch_async(concurrentQ, ^{
            sleep(3);
            NSLog(@"section %@",[NSThread currentThread]);
        });
        dispatch_async(concurrentQ, ^{
            sleep(2);
            NSLog(@"three %@",[NSThread currentThread]);
        });
        NSLog(@"end %@",[NSThread currentThread]);
    }
    /*输出结果:
     2017-10-10 21:49:34.297219+0800 GCDLearnAdvanced[8163:1586497] beagin <NSThread: 0x60000006e0c0>{number = 1, name = main}
     2017-10-10 21:49:34.297480+0800 GCDLearnAdvanced[8163:1586497] end <NSThread: 0x60000006e0c0>{number = 1, name = main}
     2017-10-10 21:49:36.302658+0800 GCDLearnAdvanced[8163:1586552] first <NSThread: 0x60000007b600>{number = 3, name = (null)}
     2017-10-10 21:49:36.302659+0800 GCDLearnAdvanced[8163:1586553] three <NSThread: 0x604000261900>{number = 4, name = (null)}
     2017-10-10 21:49:37.299347+0800 GCDLearnAdvanced[8163:1586550] section <NSThread: 0x60000007f5c0>{number = 5, name = (null)}
     */
    

    开启多条线程,并且任务同时执行。共耗时3s,节约了时间
    任务打印在begin和end之后,说明任务不是马上执行,而是将任务添加到队列之后才开始异步执行的

    队列组

    队列组可以将很多队列添加到一个组里,这样做的好处是,当这个组里所有的任务都执行完了,队列组会通过一个方法通知我们
    如多个任务并发执行同步结果:

        //多任务并发执行
        NSLog(@"group任务开始分配");
        dispatch_queue_t GlobalQ = dispatch_get_global_queue(0, 0);
        dispatch_group_t MulTaskGroup = dispatch_group_create();
        for (NSInteger i=0; i<3; i++) {
            //dispatch_group_enter(MulTaskGroup);
            dispatch_group_async(MulTaskGroup, GlobalQ, ^{
                if (i%2==0) {
                    sleep(10);
                }else{
                    sleep(2);
                }
                NSLog(@"Task%@ %@",@(i),[NSThread currentThread]);
                //dispatch_group_leave(MulTaskGroup);
            });
        }
        NSLog(@"group任务分配完毕");
        dispatch_group_notify(MulTaskGroup, dispatch_get_main_queue(), ^{
            NSLog(@"所有任务执行完毕");
        });
        dispatch_group_wait(MulTaskGroup, dispatch_time(DISPATCH_TIME_NOW, 5*NSEC_PER_SEC));
        NSLog(@"任务分配完毕 同步等待5s");
    /*输出结果:
         2017-10-12 14:32:25.620720+0800 GCDLearnAdvanced[2075:501433] group任务开始分配
         2017-10-12 14:32:25.620919+0800 GCDLearnAdvanced[2075:501433] group任务分配完毕
         2017-10-12 14:32:27.622885+0800 GCDLearnAdvanced[2075:501470] Task1 <NSThread: 0x600000269bc0>{number = 3, name = (null)}
         2017-10-12 14:32:30.622025+0800 GCDLearnAdvanced[2075:501433] 任务分配完毕 同步等待5s
         2017-10-12 14:32:35.623014+0800 GCDLearnAdvanced[2075:501472] Task0 <NSThread: 0x60c00046cf00>{number = 5, name = (null)}
         2017-10-12 14:32:35.623016+0800 GCDLearnAdvanced[2075:501481] Task2 <NSThread: 0x60000026a440>{number = 4, name = (null)}
         2017-10-12 14:32:35.623169+0800 GCDLearnAdvanced[2075:501433] 所有任务执行完毕
     */
    
    • 案例开启了三个并发异步任务,不同任务执行顺序和用时不同,但dispatch_group_notify会在所有组任务完成时发出通知。
    • dispatch_group_wait是任务完成或指定的超时时间结束会执行其block。从打印可以看出dispatch_group_wait会阻塞当前线程,所以实际中不建议放到主线程

    当有些任务并不是由group开启时 如AFNetworking网络请求,需要用到dispatch_group_enter和dispatch_group_leave,案例如下:

        //模仿上传多张图片
        NSMutableArray *imgRArr = [NSMutableArray array];
        for (NSInteger i=0; i<5; i++) {
            [imgRArr addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Null",@"imgUrl", nil]];
        }
        dispatch_group_t disGroup = dispatch_group_create();
        for (NSInteger i=0; i<imgRArr.count; i++) {
            dispatch_group_enter(disGroup);
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                /*模仿不同请求耗时不同*/
                if (i%2==0) {
                    sleep(0.5);
                }else{
                    sleep(0.1);
                }
                BOOL success = true;
                if (success) {
                    NSLog(@"顺序关系%@",@(i));
                    @synchronized(imgRArr){
                        [imgRArr replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"success%@",@(i)],@"imgUrl", nil]];
                    }
                }
                dispatch_group_leave(disGroup);
            });
        }
        dispatch_group_notify(disGroup, dispatch_get_main_queue(), ^{
            NSString *resultStr = @"";
            for (NSDictionary *rDict in imgRArr) {
                resultStr = [resultStr stringByAppendingFormat:@"%@ - ",[rDict objectForKey:@"imgUrl"]];
            }
            if (resultStr.length!=0) {
                [resultStr substringToIndex:resultStr.length-1];
            }
            NSLog(@"上传图片url %@",resultStr);
        });
    /*输出结果:
    2017-10-12 14:45:23.938217+0800 GCDLearnAdvanced[2146:531015] 顺序关系3
    2017-10-12 14:45:23.938218+0800 GCDLearnAdvanced[2146:531021] 顺序关系0
    2017-10-12 14:45:23.938218+0800 GCDLearnAdvanced[2146:531017] 顺序关系2
    2017-10-12 14:45:23.938235+0800 GCDLearnAdvanced[2146:531016] 顺序关系1
    2017-10-12 14:45:23.938410+0800 GCDLearnAdvanced[2146:531017] 顺序关系4
    2017-10-12 14:45:23.965497+0800 GCDLearnAdvanced[2146:530979] 上传图片url success0 - success1 - success2 - success3 - success4 - 
    */
    
    • dispatch_group_enter和dispatch_group_leave 必须成对出现
    • group_leave 手动标识离开队列组,调用后队列组会更新

    下一篇 iOS多线程梳理-GCD死锁

    相关参考:
    http://www.jianshu.com/p/0b0d9b1f1f19
    http://www.jianshu.com/p/2d57c72016c6

    相关文章

      网友评论

          本文标题:iOS多线程梳理-GCD

          本文链接:https://www.haomeiwen.com/subject/pmmwyxtx.html