美文网首页
GCD--dispatch_apply

GCD--dispatch_apply

作者: 初灬终 | 来源:发表于2018-12-01 23:47 被阅读2次

Submits a block to a dispatch queue for multiple invocations.
This function submits a block to a dispatch queue for multiple invocations and waits for all iterations of the task block to complete before returning. If the target queue is a concurrent queue returned by dispatch_get_global_queue, the block can be invoked concurrently, and it must therefore be reentrant-safe. Using this function with a concurrent queue can be useful as an efficient parallel for loop.
The current index of iteration is passed to each invocation of the block.

dispatch_apply直到所有任务都执行完毕,才会返回。

例如:

    dispatch_apply(5, dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT), ^(size_t n) {
        for (int i=0; i<2; i++) {
            sleep(1);
            NSLog(@"%@ -- %d",[NSThread currentThread], i);
        }
    });
    NSLog(@"all finished");

输出结果

2018-12-01 23:14:59.933527+0800 dispatch_apply-Demo[50299:2325437] <NSThread: 0x600000064fc0>{number = 1, name = main} -- 0
2018-12-01 23:14:59.933550+0800 dispatch_apply-Demo[50299:2325496] <NSThread: 0x6040002603c0>{number = 5, name = (null)} -- 0
2018-12-01 23:14:59.933560+0800 dispatch_apply-Demo[50299:2325497] <NSThread: 0x60400007fc00>{number = 4, name = (null)} -- 0
2018-12-01 23:14:59.933596+0800 dispatch_apply-Demo[50299:2325494] <NSThread: 0x60000027b040>{number = 3, name = (null)} -- 0
2018-12-01 23:15:00.934084+0800 dispatch_apply-Demo[50299:2325437] <NSThread: 0x600000064fc0>{number = 1, name = main} -- 1
2018-12-01 23:15:00.937887+0800 dispatch_apply-Demo[50299:2325497] <NSThread: 0x60400007fc00>{number = 4, name = (null)} -- 1
2018-12-01 23:15:00.937888+0800 dispatch_apply-Demo[50299:2325496] <NSThread: 0x6040002603c0>{number = 5, name = (null)} -- 1
2018-12-01 23:15:00.937980+0800 dispatch_apply-Demo[50299:2325494] <NSThread: 0x60000027b040>{number = 3, name = (null)} -- 1
2018-12-01 23:15:01.935680+0800 dispatch_apply-Demo[50299:2325437] <NSThread: 0x600000064fc0>{number = 1, name = main} -- 0
2018-12-01 23:15:02.937273+0800 dispatch_apply-Demo[50299:2325437] <NSThread: 0x600000064fc0>{number = 1, name = main} -- 1
2018-12-01 23:15:02.937622+0800 dispatch_apply-Demo[50299:2325437] all finished

相关文章

网友评论

      本文标题:GCD--dispatch_apply

      本文链接:https://www.haomeiwen.com/subject/hfrdcqtx.html