- 原文地址 http://www.cnblogs.com/sunfrog/p/3243230.html
- GCD提供两种方式支持dispatch队列同步,即dispatch组和信号量。
- 一、dispatch组(dispatch group)
- 1. 创建dispatch组
- dispatch_group_t group = dispatch_group_create();
- 2. 启动dispatch队列中的block关联到group中
- dispatch_group_async(group, queue, ^{
- // 。。。
- });
- 3. 等待group关联的block执行完毕,也可以设置超时参数
- dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
- 4. 为group设置通知一个block,当group关联的block执行完毕后,就调用这个block。类似dispatch_barrier_async。
- dispatch_group_notify(group, queue, ^{
- // 。。。
- });
- 5. 手动管理group关联的block的运行状态(或计数),进入和退出group次数必须匹配
- dispatch_group_enter(group);
- dispatch_group_leave(group);
- 所以下面的两种调用其实是等价的,
- A)
- dispatch_group_async(group, queue, ^{
- // 。。。
- });
- B)
- dispatch_group_enter(group);
- dispatch_async(queue, ^{
- //。。。
- dispatch_group_leave(group);
- });
- 所以,可以利用dispatch_group_enter、 dispatch_group_leave和dispatch_group_wait来实现同步,具体例子:http://stackoverflow.com/questions/10643797/wait-until-multiple-operations-executed-including-completion-block-afnetworki/10644282#10644282。
- 二、dispatch信号量(dispatch semaphore)
- 1. 创建信号量,可以设置信号量的资源数。0表示没有资源,调用dispatch_semaphore_wait会立即等待。
- dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
- 2. 等待信号,可以设置超时参数。该函数返回0表示得到通知,非0表示超时。
- dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
- 3. 通知信号,如果等待线程被唤醒则返回非0,否则返回0。
- dispatch_semaphore_signal(semaphore);
- 最后,还是回到生成消费者的例子,使用dispatch信号量是如何实现同步:
- dispatch_semaphore_t sem = dispatch_semaphore_create(0);
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //消费者队列
- while (condition) {
- if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 10*NSEC_PER_SEC))) //等待10秒
- continue;
- //得到数据
- }
- });
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //生产者队列
- while (condition) {
- if (!dispatch_semaphore_signal(sem))
- {
- sleep(1); //wait for a while
- continue;
- }
- //通知成功
- }
- });
dispatch同步
最新推荐文章于 2023-08-24 15:21:39 发布