GCD图文详细讲解

前言

对初学者来说,GCD似乎是一道迈不过去的坎,很多人在同步、异步、串行、并行和死锁这几个名词的漩涡中渐渐放弃治疗。本文将使用图文表并茂的方式给大家形象地解释其中的原理和规律。


线程、任务和队列的概念

1.png

异步、同步 & 并行、串行的特点

2.png

一条重要的准则

一般来说,我们使用GCD的最大目的是在新的线程中同时执行多个任务,这意味着我们需要两项条件:


  • 能开启新的线程

  • 任务可以同时执行

  • 结合以上两个条件,也就等价“开启新线程的能力 + 任务同步执行的权利”,只有在满足能力与权利这两个条件的前提下,我们才可以在同时执行多个任务。


所有组合的特点

3.png

(一)异步执行 + 并行队列

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//异步执行 + 并行队列
- ( void )asyncConcurrent{
     //创建一个并行队列
     dispatch_queue_t queue = dispatch_queue_create( "标识符" , DISPATCH_QUEUE_CONCURRENT);
 
     NSLog(@ "---start---" );
 
     //使用异步函数封装三个任务
     dispatch_async(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
 
     NSLog(@ "---end---" );
}

打印结果:

1
2
3
4
5
---start---
   ---end---
   任务3---{number = 5, name = (null)}
   任务2---{number = 4, name = (null)}
   任务1---{number = 3, name = (null)}

解释

  • 异步执行意味着

    • 可以开启新的线程

    • 任务可以先绕过不执行,回头再来执行

  • 并行队列意味着

    • 任务之间不需要排队,且具有同时被执行的“权利”

  • 两者组合后的结果

    • 开了三个新线程

    • 函数在执行时,先打印了start和end,再回头执行这三个任务

    • 这三个任务是同时执行的,没有先后,所以打印结果是“任务3-->任务2-->任务1”


步骤图

4.png

(二)异步执行 + 串行队列

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//异步执行 + 串行队列
- ( void )asyncSerial{
     //创建一个串行队列
     dispatch_queue_t queue = dispatch_queue_create( "标识符" , DISPATCH_QUEUE_SERIAL);
 
     NSLog(@ "---start---" );
     //使用异步函数封装三个任务
     dispatch_async(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
     NSLog(@ "---end---" );
}

打印结果:

1
2
3
4
5
  ---start---
  ---end---
任务1---{number = 3, name = (null)}
任务2---{number = 3, name = (null)}
任务3---{number = 3, name = (null)}

解释

  • 异步执行意味着

    • 可以开启新的线程

    • 任务可以先绕过不执行,回头再来执行

  • 串行队列意味着

    • 任务必须按添加进队列的顺序挨个执行

  • 两者组合后的结果

    • 开了一个新的子线程

    • 函数在执行时,先打印了start和end,再回头执行这三个任务

    • 这三个任务是按顺序执行的,所以打印结果是“任务1-->任务2-->任务3”

步骤图

5.png

(三)同步执行 + 并行队列

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//同步执行 + 并行队列
- ( void )syncConcurrent{
     //创建一个并行队列
     dispatch_queue_t queue = dispatch_queue_create( "标识符" , DISPATCH_QUEUE_CONCURRENT);
 
     NSLog(@ "---start---" );
     //使用同步函数封装三个任务
     dispatch_sync(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
     NSLog(@ "---end---" );
}

打印结果:

1
2
3
4
5
---start---
   任务1---{number = 1, name = main}
   任务2---{number = 1, name = main}
   任务3---{number = 1, name = main}
   ---end---

解释

  • 同步执行执行意味着

    • 不能开启新的线程

    • 任务创建后必须执行完才能往下走

  • 并行队列意味着

    • 任务必须按添加进队列的顺序挨个执行

  • 两者组合后的结果

    • 所有任务都只能在主线程中执行

    • 函数在执行时,必须按照代码的书写顺序一行一行地执行完才能继续

  • 注意事项

    • 在这里即便是并行队列,任务可以同时执行,但是由于只存在一个主线程,所以没法把任务分发到不同的线程去同步处理,其结果就是只能在主线程里按顺序挨个挨个执行了

步骤图

6.png

(四)同步执行+ 串行队列

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- ( void )syncSerial{
     //创建一个串行队列
     dispatch_queue_t queue = dispatch_queue_create( "标识符" , DISPATCH_QUEUE_SERIAL);
 
     NSLog(@ "---start---" );
     //使用异步函数封装三个任务
     dispatch_sync(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
     NSLog(@ "---end---" );
}


打印结果:

1
2
3
4
5
   ---start---
   任务1---{number = 1, name = main}
   任务2---{number = 1, name = main}
   任务3---{number = 1, name = main}
   ---end---

解释

  • 这里的执行原理和步骤图跟“同步执行+并发队列”是一样的,只要是同步执行就没法开启新的线程,所以多个任务之间也一样只能按顺序来执行,

(五)异步执行+主队列

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- ( void )asyncMain{
     //获取主队列
     dispatch_queue_t queue = dispatch_get_main_queue();
 
     NSLog(@ "---start---" );
     //使用异步函数封装三个任务
     dispatch_async(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_async(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
     NSLog(@ "---end---" );
}


打印结果:

1
2
3
4
5
   ---start---
   ---end---
   任务1---{number = 1, name = main}
   任务2---{number = 1, name = main}
   任务3---{number = 1, name = main}

解释

  • 异步执行意味着

    • 可以开启新的线程

    • 任务可以先绕过不执行,回头再来执行

  • 主队列跟串行队列的区别

    • 队列中的任务一样要按顺序执行

    • 主队列中的任务必须在主线程中执行,不允许在子线程中执行

  • 以上条件组合后得出结果:

    • 所有任务都可以先跳过,之后再来“按顺序”执行

步骤图

7.png

(六)同步执行+主队列(死锁)

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- ( void )syncMain{
     //获取主队列
     dispatch_queue_t queue = dispatch_get_main_queue();
 
     NSLog(@ "---start---" );
     //使用同步函数封装三个任务
     dispatch_sync(queue, ^{
         NSLog(@ "任务1---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务2---%@" , [NSThread currentThread]);
     });
     dispatch_sync(queue, ^{
         NSLog(@ "任务3---%@" , [NSThread currentThread]);
     });
     NSLog(@ "---end---" );
}

打印结果:

1
   ---start---

解释

  • 主队列中的任务必须按顺序挨个执行

  • 任务1要等主线程有空的时候(即主队列中的所有任务执行完)才能执行

  • 主线程要执行完“打印end”的任务后才有空

  • “任务1”和“打印end”两个任务互相等待,造成死锁

步骤图

8.png


写在结尾的话

以上就是我对GCD的基础知识和几种组合的理解,如果觉得我的博客写得还可以,欢迎关注我的博客,本人将长期为大家推出高质量的技术博客。当然,如果觉得我哪里理解有错的,也可以留下你的评论。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,对代码进行详细讲解。 首先,程序读入一个整数n,表示要求分母小于等于n的最简分数。如果n为0,则退出程序。这个部分的代码如下: ```cpp int n; while (cin >> n && n != 0) { // ... } ``` 接着,程序遍历分母为1到n-1的所有分数,找到分子分母互质的分数,加入到vector中。这个部分的代码如下: ```cpp vector<pair<int, int>> fractions; for (int i = 1; i < n; i++) { for (int j = i + 1; j <= n; j++) { if (gcd(i, j) == 1) { fractions.emplace_back(i, j); } } } ``` 这里使用了一个pair<int, int>类型的vector来存储所有的分数,pair的第一个元素表示分子,第二个元素表示分母。外层循环遍历所有的分母为1到n-1的分数,内层循环遍历所有的分母为i+1到n的分数。如果分子分母互质,则将其加入到vector中。 判断分子分母是否互质的函数gcd可以使用辗转相除法实现。这个函数的代码如下: ```cpp int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } ``` 接下来,程序对vector中的所有分数按照分数值从小到大排序。这个部分的代码如下: ```cpp sort(fractions.begin(), fractions.end(), [](auto& a, auto& b) { return a.first * b.second < b.first * a.second; }); ``` 这里使用了C++11的lambda表达式来定义比较函数。lambda表达式的形式是[捕获列表](参数列表) -> 返回值类型 { 函数体 }。这里的捕获列表为空,参数列表包含两个引用类型的参数a和b,返回值类型为bool。函数体中使用了分数的大小比较规则,即a.first/a.second < b.first/b.second等价于a.first * b.second < b.first * a.second。 最后,程序对vector中的每个分数调用simplify函数进行化简,输出结果。这个部分的代码如下: ```cpp for (auto& frac : fractions) { auto [a, b] = simplify(frac.first, frac.second); cout << a << "/" << b << " "; } cout << endl; ``` 这里使用了C++17的结构化绑定语法,在auto后面使用中括号[]来定义变量名,然后使用等号=将simplify函数返回的pair<int, int>类型的结果分别赋值给a和b。最后,程序输出化简后的分数,每个分数之间使用空格隔开,末尾再输出一个换行符。 simplify函数的实现很简单,就是对分子分母同时除以它们的最大公约数。这个函数的代码如下: ```cpp pair<int, int> simplify(int a, int b) { int g = gcd(a, b); return {a / g, b / g}; } ``` 至此,代码讲解完毕。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值