多线程-GCD

GCD常用API

  1. dispatch_queue_t 队列
  2. dispatch_async 和 dispatch_sync
  3. dispatch_after
  4. dispatch_once
  5. dispatch_set_target_queue
  6. dispatch_barrier_async
  7. dispatch_apply
  8. dispatch_suspend 和 dispatch_resume
  9. dispatch group 相关
  10. dispatch semaphore 相关

dispatch_queue_t 队列

队列有两种串行队列(Serial Diapatch Queue)和并行队列(Concurrent Dispatch Queue)

  • 串行队列:队列中可以有很多任务,但是只能向一个线程一个接一个的派发的任务(一个线程一次只能执行一个任务)
  • 并行队列:相比串行队列的一个线程,并行队列可以同时给多个线程派发任务,至于同时有多少个线程取决于当前系统的状态

创建自定义队列

  • 串行队列:dispatch_queue_create("com.xxx.xxx.test", DISPATCH_QUEUE_SERIAL)
  • 并行队列:dispatch_queue_create("com.xxx.xxx.test", DISPATCH_QUEUE_CONCURRENT)

获取系统队列

  1. dispatch_get_main_queue() 在主线程中执行的队列,因为主线程只有一个,自然是串行队列了
  2. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_XXX,0) 并行队列
    • DISPATCH_QUEUE_PRIORITY_HIGH 优先级最高
    • DISPATCH_QUEUE_PRIORITY_DEFAULT 默认优先级
    • DISPATCH_QUEUE_PRIORITY_LOW 优先级低
    • DISPATCH_QUEUE_PRIORITY_BACKGROUND 后台

注意:这些优先级不能保证实时性,因此只是大致判断

dispatch_async 和 dispatch_sync

  • dispatch_async 非同步向队列中添加任务
  • dispatch_sync 同步向队列中添加任务,如果上一个任务没有完成,那就一直等待

异步向串行队列派发任务

dispatch_queue_t queue = dispatch_queue_create("com.mtry.demo.test", DISPATCH_QUEUE_SERIAL);
for(NSInteger i = 0; i < 3; i++)
{    
    NSLog(@"进入队列:%ld", i);
    dispatch_async(queue, ^{
        sleep(1);
        NSLog(@"执行任务:%ld", i);
    });
}

结果(注意输出时间)
14:21:24.554 ObjectiveDemo[1030:69346] 进入队列:0
14:21:24.554 ObjectiveDemo[1030:69346] 进入队列:1
14:21:24.555 ObjectiveDemo[1030:69346] 进入队列:2
14:21:25.558 ObjectiveDemo[1030:69388] 执行任务:0
14:21:26.561 ObjectiveDemo[1030:69388] 执行任务:1
14:21:27.561 ObjectiveDemo[1030:69388] 执行任务:2

解释
并行队列中几乎是同时加进3个任务,然后派发任务,可以看到不是sleep(1)后同时打出日志,而是完成一个之后再派发一个任务

同步向并行队列派发任务

dispatch_queue_t queue = dispatch_queue_create("com.mtry.demo.test", DISPATCH_QUEUE_CONCURRENT);
for(NSInteger i = 0; i < 3; i++)
{
    NSLog(@"进入队列:%ld", i);
    dispatch_sync(queue, ^{
        sleep(1);
        NSLog(@"执行任务:%ld", i);
    });
}

结果(注意输出时间)
14:47:07.616 ObjectiveDemo[1055:74849] 进入队列:0
14:47:08.616 ObjectiveDemo[1055:74849] 执行任务:0
14:47:08.617 ObjectiveDemo[1055:74849] 进入队列:1
14:47:09.618 ObjectiveDemo[1055:74849] 执行任务:1
14:47:09.618 ObjectiveDemo[1055:74849] 进入队列:2
14:47:10.619 ObjectiveDemo[1055:74849] 执行任务:2

解释
由于是一个任务完成之后,再添加一个新的任务,所以队列中只会存在一个派发中的任务

注意:向队列中同步或异步添加任务,队列向线程串行或并行派发任务

死锁现象

串行队列中异步一个任务,然后在任务中向队列同步一个任务,造成死锁。观察下面两段代码

dispatch_queue_t queue = dispatch_queue_create("com.mtry.demo.test", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
    NSLog(@"1");
    dispatch_sync(queue, ^{
        NSLog(@"2");
    });
    NSLog(@"3");
});

结果:16:16:30.282 ObjectiveDemo[1248:97831] 1
dispatch_queue_t queue = dispatch_queue_create("com.mtry.demo.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
    NSLog(@"1");    
    dispatch_sync(queue, ^{
        NSLog(@"2");
    });
    NSLog(@"3");
});

结果
16:17:14.916 ObjectiveDemo[1260:98640] 1    
16:17:14.916 ObjectiveDemo[1260:98640] 2
16:17:14.916 ObjectiveDemo[1260:98640] 3

现象:串行队列死锁,并行队列正常


解释:按照串行派发任务是完成一个任务再从队列中取,输出的顺序是1 3 2,按照同步操作输出的顺序是1 2 3,只有输出1不矛盾,然后就执行不了了。并行派发任务不需要等待,有同步过来的就可以直接执行,然后再执行后面的,所以正常了

dispatch_after延迟调用

API
void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block)

使用
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
dispatch_after(time, dispatch_get_main_queue(), ^{
    NSLog(@"done");
});

解释
延迟大致3s(不是准确时间)在主线程调用,当然也可以通过修改队列让其在子线程上执行

dispatch_time_t

dispatch_time_t 可以通过 dispatch_time 或 dispatch_walltime 函数生成

//dispatch_time 生成相对时间,比如相对现在延迟3.0s
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
//dispatch_walltime 生成绝对时间,指定某时间2020年2月2日 2时2分2秒 执行任务
dispatch_time_t getDispatchTimeForDate(NSDate *date)
{
    NSTimeInterval interval;
    double second, subSecond;
    struct timespec time;
    dispatch_time_t milestone;

    interval = [date timeIntervalSince1970];
    subSecond = modf(interval, &second);
    time.tv_sec = second;
    time.tv_nsec = subSecond * NSEC_PER_SEC;
    milestone = dispatch_walltime(&time, 0);

    return milestone;
}

dispatch_once

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    //初始化;
});

相比使用静态变量标记,dispatch_once是线程安全的

dispatch_set_target_queue

修改优先级

使用dispatch_queue_create创建的队列都是默认优先级,如果需要修改优先级可以先通过dispatch_get_global_queue生成一个想要的优先级,然后通过dispatch_set_target_queue进行指定修改

修改串并行队列

dispatch_queue_t queue1 = dispatch_queue_create("com.mtry.demo.test1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue2 = dispatch_queue_create("com.mtry.demo.test2", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t queue3 = dispatch_queue_create("com.mtry.demo.test3", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t queue4 = dispatch_queue_create("com.mtry.demo.test4", DISPATCH_QUEUE_CONCURRENT);
dispatch_set_target_queue(queue4, queue3);
dispatch_set_target_queue(queue3, queue2);
dispatch_set_target_queue(queue2, queue1);
NSInteger i = 0;
for(; i < 3; i++)
{
    dispatch_async(queue1, ^{
        NSLog(@"%ld", i);
    });
}
for(; i < 6; i++)
{
    dispatch_async(queue2, ^{
    NSLog(@"%ld", i);
    });
}
for(; i < 9; i++)
{
    dispatch_async(queue3, ^{
        NSLog(@"%ld", i);
    });
}
for(; i < 12; i++)
{
    dispatch_async(queue4, ^{
        NSLog(@"%ld", i);
    });
}

结果:0 1 2 3 4 5 6 7 8 9 10 11

解释:可以把整个修改看成一颗树,如果根节点是串行,那么所有节点全为串行,反之全为并行

dispatch_barrier_async

当我们在操作数据库时,会经常遇到,数据的并行读取,写入时又要考虑数据竞争问题,dispatch_barrier_async 是一种解决方案

NSMutableArray *array = @[@"1", @"2", @"3"].mutableCopy;
dispatch_queue_t queue = dispatch_queue_create("com.mtry.demo.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{NSLog(@"%@", array[0]);});
dispatch_async(queue, ^{NSLog(@"%@", array[1]);});
dispatch_async(queue, ^{NSLog(@"%@", array[2]);});
dispatch_barrier_async(queue, ^{[array addObject:@"4"]; NSLog(@"add 4");});
dispatch_async(queue, ^{NSLog(@"%@", array[0]);});
dispatch_async(queue, ^{NSLog(@"%@", array[1]);});
dispatch_async(queue, ^{NSLog(@"%@", array[2]);});
dispatch_async(queue, ^{NSLog(@"%@", array[3]);});

结果
09:10:21.698 ObjectiveDemo[670:9144] 1
09:10:21.698 ObjectiveDemo[670:9162] 3
09:10:21.698 ObjectiveDemo[670:9137] 2
09:10:21.698 ObjectiveDemo[670:9137] add 4
09:10:21.698 ObjectiveDemo[670:9137] 2
09:10:21.698 ObjectiveDemo[670:9162] 1
09:10:21.698 ObjectiveDemo[670:9144] 3
09:10:21.698 ObjectiveDemo[670:9148] 4

前面3个任务无法控制顺序,但是一定是完成之后才执行dispatch_barrier_async的任务,同样dispatch_barrier_async完成之后才会执行下面4个任务

dispatch_apply

指定次数将指定的Block追加到队列中,并等待全部只执行结束

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(5, queue, ^(size_t index) {
    NSLog(@"%ld", index);
});
NSLog(@"done");

结果
10:29:04.906 ObjectiveDemo[1407:34296] 0
10:29:04.906 ObjectiveDemo[1407:34296] 2
10:29:04.906 ObjectiveDemo[1407:34296] 3
10:29:04.906 ObjectiveDemo[1407:34319] 1
10:29:04.907 ObjectiveDemo[1407:34320] 4
10:29:04.907 ObjectiveDemo[1407:34296] done

dispatch_suspend 和 dispatch_resume

挂起和恢复派发队列中的任务。挂起和恢复主要针对是向线程派发任务操作,不影响向队列中添加任务,已经派发出去的任务自然也影响不了

  • 挂起队列:dispatch_suspend(queue)
  • 恢复队列:dispatch_resume(queue)

注意:挂起和恢复只能通过dispatch_queue_create创建的队列,不能操作dispatch_get_main_queue 和 dispatch_get_global_queue 生成的队列。YY一下系统队列应该是全局共享的,你挂起了,其它地方就会莫名其妙的停止了,出于安全的还是挂起无效吧

dispatch group 相关

队列中的任务全部结束时响应dispatch_group_notify的操作

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{NSLog(@"1");});
dispatch_group_async(group, queue, ^{NSLog(@"2");});
dispatch_group_async(group, queue, ^{NSLog(@"3");});
dispatch_group_notify(group, queue, ^{NSLog(@"done");});

结果
11:26:23.431 ObjectiveDemo[1515:48508] 1
11:26:23.431 ObjectiveDemo[1515:48603] 3
11:26:23.431 ObjectiveDemo[1515:48520] 2
11:26:23.432 ObjectiveDemo[1515:48520] done

指定等待时间就响应操作

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{NSLog(@"1");});
dispatch_group_async(group, queue, ^{NSLog(@"2");});
dispatch_group_async(group, queue, ^{NSLog(@"3");});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"done");

结果
11:30:37.824 ObjectiveDemo[1532:50167] 2
11:30:37.824 ObjectiveDemo[1532:50157] 1
11:30:37.824 ObjectiveDemo[1532:50181] 3
11:30:37.825 ObjectiveDemo[1532:50133] done

DISPATCH_TIME_FOREVER 是 dispatch_time_t 类型,表示永久等待。当然也可以自己创建指定时间,比如下面代码等待1s

dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC);
long result = dispatch_group_wait(group, time);
if(result == 0)
{
    //队列中的任务全部完成
}
else
{
    //队列中还有任务没有完成
}

dispatch_group_enter 和 dispatch_group_leave

当并行派发队列中嵌套一个并行派发队列时可以使用dispatch_group_enter 和 dispatch_group_leave

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t queue2 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue1, ^{
    dispatch_group_enter(group);
    NSLog(@"1");
    dispatch_async(queue2, ^{
        NSLog(@"2");
        dispatch_group_leave(group);
    });
});
dispatch_group_async(group, queue1, ^{
    dispatch_group_enter(group);
    NSLog(@"3");
    dispatch_async(queue2, ^{
        NSLog(@"4");
        dispatch_group_leave(group);
    });
});
dispatch_group_notify(group, queue1, ^{
    NSLog(@"done");
});

结果
11:47:10.887 ObjectiveDemo[1555:55580] 3
11:47:10.887 ObjectiveDemo[1555:55586] 1
11:47:10.887 ObjectiveDemo[1555:55586] 2
11:47:10.887 ObjectiveDemo[1555:55580] 4
11:47:10.888 ObjectiveDemo[1555:55580] done

dispatch semaphore 相关

可以实现并发,当然如果实现原子锁也一样了,把并发数改成1就可以了。以下是并发的例子

//最大并发数
NSInteger maxConcurrent = 2;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(maxConcurrent);
for(NSInteger i = 0; i < 6; i++)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"执行任务:%ld", i);
        sleep(1);
        dispatch_semaphore_signal(semaphore);
    });
}

结果(注意观察输出时间)    
13:20:40.683 ObjectiveDemo[1632:74564] 执行任务:1
13:20:40.683 ObjectiveDemo[1632:74484] 执行任务:0
13:20:41.688 ObjectiveDemo[1632:74568] 执行任务:2
13:20:41.688 ObjectiveDemo[1632:74477] 执行任务:3
13:20:42.689 ObjectiveDemo[1632:74585] 执行任务:4
13:20:42.689 ObjectiveDemo[1632:74586] 执行任务:5

dispatch_semaphore_wait 设置的时间参数是DISPATCH_TIME_FOREVER(dispatch_time_t),表示永久等待,当semaphore的计数大于等于1时,向下执行同时计数减1,如果计数为0永久等待,调用dispatch_semaphore_signal时,计数加1时间参数可以自己生成,使用与dispatch_group_wait类似

参考资料

《Objective-C高级编程 iOS与OS X多线程和内存管理》

你可能感兴趣的:(多线程-GCD)