libdispatch源码分析—dispatch_group

创建组

dispatch_group_t
dispatch_group_create(void)
{
    dispatch_group_t dg = _dispatch_alloc(DISPATCH_VTABLE(group),
            sizeof(struct dispatch_semaphore_s));
    _dispatch_semaphore_init(LONG_MAX, dg);
    return dg;
}
  1. 调用 _dispatch_alloc() 创建
  2. 调用 _dispatch_semaphore_init() 初始化
    2.1 初始化 dispatch_semaphore_t 结构体的计数器、执行队列、目标值

进入组

void
dispatch_group_enter(dispatch_group_t dg)
{
    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;

    (void)dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
}
  1. 调用 dispatch_semaphore_wait() 加锁等待,返回值为等待数量
    1. 信号量计数器先自减 value,然后返回.
    2. value > 0 返回 0 表示目前 waitor 数量为0,因为传入的 value 无穷大,所以到此返回。
      因此,调用 group_enter() 之后,当前线程不会被阻塞。

离开组

void
dispatch_group_leave(dispatch_group_t dg)
{
    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;
    dispatch_atomic_release_barrier();
    long value = dispatch_atomic_inc2o(dsema, dsema_value);
    if (slowpath(value == LONG_MIN)) {
        DISPATCH_CLIENT_CRASH("Unbalanced call to dispatch_group_leave()");
    }
    if (slowpath(value == dsema->dsema_orig)) {
        (void)_dispatch_group_wake(dsema);
    }
}
  1. 信号量计数器先自加 value,然后返回.
  2. 如果自加后的value 为 dsema_orig 调用 _dispatch_group_wake() 唤醒notify

设置组监控

#ifdef __BLOCKS__
void
dispatch_group_notify(dispatch_group_t dg, dispatch_queue_t dq,
        dispatch_block_t db)
{
    dispatch_group_notify_f(dg, dq, _dispatch_Block_copy(db),
            _dispatch_call_block_and_release);
}
#endif

void
dispatch_group_notify_f(dispatch_group_t dg, dispatch_queue_t dq, void *ctxt,
        void (*func)(void *))
{
    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;
    struct dispatch_sema_notify_s *dsn, *prev;

    // FIXME -- this should be updated to use the continuation cache
    while (!(dsn = calloc(1, sizeof(*dsn)))) {
        sleep(1);
    }

    dsn->dsn_queue = dq;
    dsn->dsn_ctxt = ctxt;
    dsn->dsn_func = func;
    _dispatch_retain(dq);
    dispatch_atomic_store_barrier();
    prev = dispatch_atomic_xchg2o(dsema, dsema_notify_tail, dsn);
    if (fastpath(prev)) {
        prev->dsn_next = dsn;
    } else {
        _dispatch_retain(dg);
        (void)dispatch_atomic_xchg2o(dsema, dsema_notify_head, dsn);
        if (dsema->dsema_value == dsema->dsema_orig) {
            _dispatch_group_wake(dsema);
        }
    }
}
  1. 调用 dispatch_group_notify_f() 传入组,执行队列,block,block调用方法指针。
    1. 初始化一个 dispatch_sema_notify_s 结构体 dsn
    2. 在 group 中,notify 为一个链表,此时调用 dispatch_atomic_xchg2o 获取前驱节点。
    3. 如果找到前驱节点,那么链接 dsn;
    4. 如果没找到前驱节点,把 dsn 作为首节点
    5. 检查所有任务是否执行完毕

组唤醒

static long
_dispatch_group_wake(dispatch_semaphore_t dsema)
{
    struct dispatch_sema_notify_s *next, *head, *tail = NULL;
    long rval;

    head = dispatch_atomic_xchg2o(dsema, dsema_notify_head, NULL);
    if (head) {
        // snapshot before anything is notified/woken <rdar://problem/8554546>
        tail = dispatch_atomic_xchg2o(dsema, dsema_notify_tail, NULL);
    }
    rval = dispatch_atomic_xchg2o(dsema, dsema_group_waiters, 0);
    if (rval) {
        // wake group waiters
#if USE_MACH_SEM
        _dispatch_semaphore_create_port(&dsema->dsema_waiter_port);
        do {
            kern_return_t kr = semaphore_signal(dsema->dsema_waiter_port);
            DISPATCH_SEMAPHORE_VERIFY_KR(kr);
        } while (--rval);
#endif
    }
    if (head) {
        // async group notify blocks
        do {
            dispatch_async_f(head->dsn_queue, head->dsn_ctxt, head->dsn_func);
            _dispatch_release(head->dsn_queue);
            next = fastpath(head->dsn_next);
            if (!next && head != tail) {
                while (!(next = fastpath(head->dsn_next))) {
                    _dispatch_hardware_pause();
                }
            }
            free(head);
        } while ((head = next));
        _dispatch_release(dsema);
    }
    return 0;
}

每个组leave的时候,都会检查是否所有任务都已经结束,然后等到所有任务都结束后,会调用wake 函数来执行 notify

  1. 获取notify链表的头/尾结点和等待执行的任务数
  2. 如果有任务在等待,向内核发送信号,唤起等待任务
  3. 异步执行链表中所有的 notify

组等待

long
dispatch_group_wait(dispatch_group_t dg, dispatch_time_t timeout)
{
    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;

    if (dsema->dsema_value == dsema->dsema_orig) {
        return 0;
    }
    if (timeout == 0) {
#if USE_MACH_SEM
        return KERN_OPERATION_TIMED_OUT;
#endif
    }
    return _dispatch_group_wait_slow(dsema, timeout);
}

static long
_dispatch_group_wait_slow(dispatch_semaphore_t dsema, dispatch_time_t timeout)
{
    long orig;

#if USE_MACH_SEM
    mach_timespec_t _timeout;
    kern_return_t kr;
#endif

again:
    // check before we cause another signal to be sent by incrementing
    // dsema->dsema_group_waiters
    if (dsema->dsema_value == dsema->dsema_orig) {
        return _dispatch_group_wake(dsema);
    }
    // Mach semaphores appear to sometimes spuriously wake up. Therefore,
    // we keep a parallel count of the number of times a Mach semaphore is
    // signaled (6880961).
    (void)dispatch_atomic_inc2o(dsema, dsema_group_waiters);
    // check the values again in case we need to wake any threads
    if (dsema->dsema_value == dsema->dsema_orig) {
        return _dispatch_group_wake(dsema);
    }

#if USE_MACH_SEM
    _dispatch_semaphore_create_port(&dsema->dsema_port);
#endif

    // From xnu/osfmk/kern/sync_sema.c:
    // wait_semaphore->count = -1; /* we don't keep an actual count */
    //
    // The code above does not match the documentation, and that fact is
    // not surprising. The documented semantics are clumsy to use in any
    // practical way. The above hack effectively tricks the rest of the
    // Mach semaphore logic to behave like the libdispatch algorithm.

    switch (timeout) {
    default:
#if USE_MACH_SEM
        do {
            uint64_t nsec = _dispatch_timeout(timeout);
            _timeout.tv_sec = (typeof(_timeout.tv_sec))(nsec / NSEC_PER_SEC);
            _timeout.tv_nsec = (typeof(_timeout.tv_nsec))(nsec % NSEC_PER_SEC);
            kr = slowpath(semaphore_timedwait(dsema->dsema_waiter_port,
                    _timeout));
        } while (kr == KERN_ABORTED);

        if (kr != KERN_OPERATION_TIMED_OUT) {
            DISPATCH_SEMAPHORE_VERIFY_KR(kr);
            break;
        }
#endif
        // Fall through and try to undo the earlier change to
        // dsema->dsema_group_waiters
    case DISPATCH_TIME_NOW:
        while ((orig = dsema->dsema_group_waiters)) {
            if (dispatch_atomic_cmpxchg2o(dsema, dsema_group_waiters, orig,
                    orig - 1)) {
#endif
            }
        }
        // Another thread called semaphore_signal().
        // Fall through and drain the wakeup.
    case DISPATCH_TIME_FOREVER:
#if USE_MACH_SEM
        do {
            kr = semaphore_wait(dsema->dsema_waiter_port);
        } while (kr == KERN_ABORTED);
        DISPATCH_SEMAPHORE_VERIFY_KR(kr);
#endif
        break;
    }

    goto again;
}
  1. 先检查所有的任务是否都执行完了,则调用wake,【并且处理特殊情况】
  2. 然后调用 semaphore_wait() 向 dsema->dsema_waiter_port 内核发送等待信号。

总结

信号量结构体里面,有一个计数器,每次wait 和 signal 的时候,都会改这个计数器,wait 的时候如果达到临界值,计数器为0,就会向内核发送中断的信号,体现为不继续向下执行。如果sign 被调用,如果没达到临界值,那就继续计数器增加,如果达到临界值,为0,就会向内核发送唤醒信号,然后让中断的代码继续执行。

对于group,实际就是创建信号量计数为long_max的信号量。所以不会等待,所有添加到group的任务都能立即执行。notify函数作用就是把block加到信号量里面的一个链表中,等所有的group都执行完后,遍历这个链表,执行notify。【不涉及内核的中断和恢复】
但是 group_wait 就和上面信号量等待类似,涉及内核的中断和恢复了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 本文用来介绍 iOS 多线程中 GCD 的相关知识以及使用方法。这大概是史上最详细、清晰的关于 GCD 的详细讲...
    花花世界的孤独行者阅读 491评论 0 1
  • 一:base.h 二:block.h 1. dispatch_block_flags:DISPATCH_BLOCK...
    小暖风阅读 2,391评论 0 0
  • 文用来介绍 iOS 多线程中 GCD 的相关知识以及使用方法。通过本文,您将了解到: 1. GCD 简介 2. G...
    晓_我想去环游世界阅读 1,128评论 2 8
  • 1 这几天断断续续看了《死亡诗社》,后半段看的泪流满面,陈先生关切的问我怎么了,怎么哭的“梨花带雨”的。 我哽咽说...
    双向养育良耳阅读 713评论 1 1
  • 天昏暗着,雨将是要下了吧。反正周五也是清静的,来点雨水浇灌,也是好的。洗洗这个小镇的红瓦灰墙,铜钟与铜灰色的马路。...
    炉灰上的火焰阅读 190评论 0 2