GCD之并行串行区别

时间:2024-11-12 19:05:56

1.用户自定义线程队列,创建时很容易创建 注意创建时的第一个参数:标记值,方便调试查看

1
2
dispatch_queue_t serialqueue=dispatch_queue_create("serialqueue", DISPATCH_QUEUE_SERIAL);//串行线程队列
dispatch_queue_t concurrentqueue=dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);//并行线程队列

2.创建之后那如何验证它是串行还是并行的呢?

第一种:

1
2
3
4
5
6
dispatch_apply(5, concurrentqueue, ^(size_t index) {
        NSLog(@"%ld",index);
    });
    dispatch_apply(5, serialqueue, ^(size_t index) {
        NSLog(@"%ld",index);
    });

输出结果:

GCD之并行串行区别

第一个循环输出无序第一个有序,可以看出第一个是多线程并行,第二哥是单线程串行。

第二种:

(1)串行的验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
dispatch_async(serialqueue, ^{
        NSLog(@"1");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"2");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"3");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"4");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"5");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"6");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"7");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"8");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"9");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"10");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"11");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"12");
    });
    dispatch_async(serialqueue, ^{
        NSLog(@"13");
    });

输出结果:

GCD之并行串行区别

可以看到输出结果连续。

(2)并行的验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
dispatch_async(concurrentqueue, ^{
        NSLog(@"1");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"2");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"3");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"4");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"5");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"6");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"7");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"8");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"9");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"10");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"11");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"12");
    });
    dispatch_async(concurrentqueue, ^{
        NSLog(@"13");
    });

输出结果:

GCD之并行串行区别

由此可见:输出结果不连续。

3.从上面的两个输出结果可以看出:串行是在一个线程上执行任务,而并行是在多个线程上执行任务。