GCD之死锁

时间:2020-12-14 16:01:38

GCD相当好用,但用不好就会死锁,始终要记着这样一句秘籍:

不要在串行队列放dispatch_sync、dispatch_apply

下面看几个例子

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
40
41
// 防死锁秘籍:不要在串行队列放dispatch_sync、dispatch_apply
   // 死锁  主线程调用dispatch_apply
    dispatch_async(dispatch_get_main_queue(), ^{
        dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
            NSLog(@"%ld",i);
            NSLog(@"%d",55);
        });
      });
    NSLog(@"%d",999);
    //死锁 主线程调用dispatch_apply
    dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
        NSLog(@"%ld",i);
        NSLog(@"%d",777);
    });
    
    
   //不死锁
    dispatch_queue_t queue=  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_apply(5, queue, ^(size_t i) {
        NSLog(@"%ld",i);
         NSLog(@"%d",66);
    });
    NSLog(@"%d",88);
    //不死锁
    dispatch_async(queue, ^{
        dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
            NSLog(@"%ld",i);
        });
    });
//    //不死锁
    dispatch_async(queue,^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"test");
        });
    });
    //死锁
    dispatch_sync(queue,^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"test");
        });
    });