GCD

本文介绍了GCD(Grand Central Dispatch),它是苹果为多核设备提供的线程管理工具,能自动利用多核CPU并管理线程生命周期。通过任务和队列的概念,开发者可以定制任务并提交到队列,实现并发执行。GCD还提供了多种函数用于线程通讯和控制。

一 简介

1 强大的中枢调度器

2 纯C语言提供非常强大的函数

二 优势

1 是苹果公司为多核并行运算提出的解决方案

2 会自动利用更多的CPU内核

3 会自动管理线程的生命周期

4 不需要编写线程相关的代码,只需要提交任务

三 核心概念

任务和队列

1 定制任务

2 将任务添加到队列中

四 常用函数

1 dispatch_async(<#dispatch_queue_t queue#>, <#^(void)block#>); // 可以开线程
2 dispatch_sync(<#dispatch_queue_t queue#>, <#^(void)block#>);  // 不会开线程
(1)并发队列:(Concurrent Dispatch Queue)

可以让多个任务同时执行 ,具备开线程的能力,在dispatch_async 下才能开新线程

五 常见组合

<span style="font-size:12px;">/**
 *  异步函数 + 并发队列 : 会开线程
 */
- (void)asyncConcurrent
{
    // 1 创建一个并发队列
    // label 队列名字
    // attr  并行还是串行
    dispatch_queue_t queue = dispatch_queue_create("download.queue", DISPATCH_QUEUE_CONCURRENT);
    // 2 系统默认的全局并发队列
    // identifier 优先级
    // flag 默认 0
    dispatch_queue_t globelQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"-- %@", [NSThread currentThread]);
        }
    });
}

/**
 *  同步函数 + 并发队列 : 不会开线程
 */
- (void)syncConcurrent
{
    dispatch_queue_t globelQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_sync(globelQueue, ^{
        for (int i = 0; i < 10; i++) {
            NSLog(@"-- %@", [NSThread currentThread]);
        }
    });
}

/**
 *  异步函数 + 串行队列 : 会开线程, 任务是串行的
 */
- (void)asyncSerial
{
    // 1 创建串行队列
    dispatch_queue_t queue = dispatch_queue_create("serial.queue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSLog(@"1-- %@", [NSThread currentThread]);
        
    });
    dispatch_async(queue, ^{
        NSLog(@"2-- %@", [NSThread currentThread]);
        
    });
    dispatch_async(queue, ^{
        NSLog(@"3-- %@", [NSThread currentThread]);
        
    });
}

/**
 *  同步函数 + 串行队列 : 不会开线程, 任务是串行的
 */
- (void)syncSerial
{
    // 1 创建串行队列
    dispatch_queue_t queue = dispatch_queue_create("serial.queue", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue, ^{
        NSLog(@"1-- %@", [NSThread currentThread]);
        
    });
    dispatch_sync(queue, ^{
        NSLog(@"2-- %@", [NSThread currentThread]);
        
    });
    dispatch_sync(queue, ^{
        NSLog(@"3-- %@", [NSThread currentThread]);
        
    });
}

/**
 *  主队列 : 任何性质的队列 都会在主线程执行任务 不开线程
 */
- (void)asyncMain
{
    // 1 创建串行队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        NSLog(@"1-- %@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"2-- %@", [NSThread currentThread]);
        
    });
    dispatch_async(queue, ^{
        NSLog(@"3-- %@", [NSThread currentThread]);
        
    });
}

/**
 *  1 主队列
 *  2 等待 syncMain 函数执行完成 才会 执行 NSLog(@"1-- %@", [NSThread currentThread]); 结果是互相等待 卡死了主线程
 */
- (void)syncMain
{
    // 1 创建串行队列
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue, ^{
        NSLog(@"1-- %@", [NSThread currentThread]);
    });
    dispatch_sync(queue, ^{
        NSLog(@"2-- %@", [NSThread currentThread]);
        
    });
    dispatch_sync(queue, ^{
        NSLog(@"3-- %@", [NSThread currentThread]);
        
    });
}</span>



六 线程通讯

// 线程通讯
- (void)connectToGCD
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *URL = [NSURL URLWithString:@""];
        NSData *data = [NSData dataWithContentsOfURL:URL];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = image;
        });
    });
}
 


七 常用函数

<span style="font-size:12px;">/**
 *  延迟执行
 */
- (void)delayToDo
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"xix");
    });
}

/**
 *  barrier
 */
- (void)barrier
{
    dispatch_queue_t queue = dispatch_queue_create("download.queue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        for (int i = 1; i < 10; i++) {
            NSLog(@"1 -- %@", [NSThread currentThread]);
        }
        
    });
    dispatch_async(queue, ^{
        for (int i = 1; i < 10; i++) {
            NSLog(@"2 -- %@", [NSThread currentThread]);
        }
    });
    // queue 不能是全局的并发队列
    // 前面的任务先执行,自己再执行,后面再执行
    dispatch_barrier_async(queue, ^{
        for (int i = 1; i < 10; i++) {
            NSLog(@"3 -- %@", [NSThread currentThread]);
        }

    });
    dispatch_async(queue, ^{
        for (int i = 1; i < 10; i++) {
            NSLog(@"4 -- %@", [NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 1; i < 10; i++) {
            NSLog(@"5 -- %@", [NSThread currentThread]);
        }
    });
}</span>

/**
 *  只执行一次
 */
- (void)once
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"Run");
    });
}

/**
 *  快速同时遍历
 */
- (void)quickToIterate
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_apply(10, queue, ^(size_t index) {
        NSLog(@"index - %zd", index);
    });
    // 1 查看沙盒所有文件
    NSFileManager *mgr = [NSFileManager defaultManager];
    NSArray *pathArray = [mgr subpathsAtPath:<#(nonnull NSString *)#>];
} 

/**
 *  对列组
 */
- (void)GCDGroup
{
    dispatch_queue_t globelQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, globelQueue, ^{
        NSURL *url = [NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fa.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2Fd1160924ab18972b0c6e3752e0cd7b899f510ad5.jpg&thumburl=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D827020255%2C4071626112%26fm%3D21%26gp%3D0.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.image1 = [UIImage imageWithData:data];
        
    });
    dispatch_group_async(group, globelQueue, ^{
        NSURL *url = [NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fv1.qzone.cc%2Fpic%2F201510%2F31%2F11%2F17%2F563432b7977c7764.jpeg%2521600x600.jpg&thumburl=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D1100963527%2C1982157674%26fm%3D21%26gp%3D0.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.image2 = [UIImage imageWithData:data];
    });
    dispatch_group_notify(group, globelQueue, ^{
       // 开启新的图形上下文
        UIGraphicsBeginImageContext(CGSizeMake(100, 100));
        // 绘制图片
        [self.image1 drawAsPatternInRect:CGRectMake(0, 0, 50, 50)];
        [self.image2 drawAsPatternInRect:CGRectMake(50, 0, 50, 50)];
        // 取得上下文中的图片
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭图形上下文
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = image;
        });
    });
    
}





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值