GCD之dispatch queue

通过与线程池的配合,dispatch queue分为下面两种:而系统默认就有一个串行队列main_queue和并行队列global_queue
Serial Dispatch Queue -- 线程池只提供一个线程用来执行任务,所以后一个任务必须等到前一个任务执行结束才能开始。
Concurrent Dispatch Queue -- 线程池提供多个线程来执行任务,所以可以按序启动多个任务并发执行。

而系统默认就有一个串行队列main_queue和并行队列global_queue

dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
dispatch_queue_t mainQ = dispatch_get_main_queue();  

通常,我们可以在global_queue中做一些long-running的任务,完成后在main_queue中更新UI,避免UI阻塞,无法响应用户操作:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        // long-running task  
        dispatch_async(dispatch_get_main_queue(), ^{  
            // update UI  
        });  
    });  
Serial quque(private dispatch queue)

为了验证Serial queue的FIFO特性,写了如下的验证代码:发现的确是顺序执行的。

   NSDate *da = [NSDate date];
   NSString *daStr = [da description];
   const char *queueName = [daStr UTF8String];
   dispatch_queue_t myQueue = dispatch_queue_create(queueName, DISPATCH_QUEUE_SERIAL);
   
   dispatch_async(myQueue, ^{
       [NSThread sleepForTimeInterval:6];
       NSLog(@"[NSThread sleepForTimeInterval:6];");
   });
   
   dispatch_async(myQueue, ^{
       [NSThread sleepForTimeInterval:3];
       NSLog(@"[NSThread sleepForTimeInterval:3];");
   });
   
   dispatch_async(myQueue, ^{
       [NSThread sleepForTimeInterval:1];
       NSLog(@"[NSThread sleepForTimeInterval:1];");
   });

运行结果为:

2018-03-02 14:21:01.345524+0800 平常测试[7805:1368123] [NSThread sleepForTimeInterval:6];
2018-03-02 14:21:04.349350+0800 平常测试[7805:1368123] [NSThread sleepForTimeInterval:3];
2018-03-02 14:21:05.354546+0800 平常测试[7805:1368123] [NSThread sleepForTimeInterval:1];
Concurrent queue(global dispatch queue):

可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.

dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(myQueue, ^{
        [NSThread sleepForTimeInterval:6];
        NSLog(@"[NSThread sleepForTimeInterval:6];");
    });
    
    dispatch_async(myQueue, ^{
        [NSThread sleepForTimeInterval:3];
        NSLog(@"[NSThread sleepForTimeInterval:3];");
    });
    
    dispatch_async(myQueue, ^{
        [NSThread sleepForTimeInterval:1];
        NSLog(@"[NSThread sleepForTimeInterval:1];");
    });

运行结果为:

2018-03-02 15:25:59.861636+0800 平常测试[7883:1389164] [NSThread sleepForTimeInterval:1];
2018-03-02 15:26:01.860329+0800 平常测试[7883:1389161] [NSThread sleepForTimeInterval:3];
2018-03-02 15:26:04.861785+0800 平常测试[7883:1389163] [NSThread sleepForTimeInterval:6];

你可能感兴趣的:(GCD之dispatch queue)