• dispatch_group_t


    Dispatch group用来阻塞一个线程,直到一个或多个任务完成执行。有时候你必须等待任务完成的结果,然后才能继续后面的处理。dispatch group也可以替代线程join。


    基本的流程是设置一个组,dispatch任务到queue,然后等待结果。你需要使用 dispatch_group_async 函数,会关联任务到相关的组和queue。使用 dispatch_group_wait 等待一组任务完成。

    第一种用法
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();

    // Add a task to the group
    dispatch_group_async(group, queue, ^{
       // Some asynchronous work
    });

    // Do some other work while the tasks execute.

    // When you cannot make any more forward progress,
    // wait on the group to block the current thread.
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

    // Release the group when it is no longer needed.
    dispatch_release(group);

    第二种方式

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
    [NSThread sleepForTimeInterval:1];
    NSLog(@"group1");
    });
    dispatch_group_async(group, queue, ^{
    [NSThread sleepForTimeInterval:2];
    NSLog(@"group2");
    });
    dispatch_group_async(group, queue, ^{
    [NSThread sleepForTimeInterval:3];
    NSLog(@"group3");
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"updateUi");
    });
    dispatch_release(group);

    dispatch_group_async是异步的方法,运行后可以看到打印结果:

    2012-09-25 16:04:16.737 gcdTest[43328:11303] group1
    2012-09-25 16:04:17.738 gcdTest[43328:12a1b] group2
    2012-09-25 16:04:18.738 gcdTest[43328:13003] group3
    2012-09-25 16:04:18.739 gcdTest[43328:f803] updateUi

    每个一秒打印一个,当第三个任务执行后,upadteUi被打印。

  • 相关阅读:
    Nginx流量拷贝
    Nginx基于站点目录和文件的URL访问控制
    Nginx禁止ip访问或非法域名访问
    Nginx动静分离
    Nginx隐藏式跳转(浏览器URL跳转后保持不变)
    Harbor镜像仓库(含clair镜像扫描)
    Pod的QoS服务质量等级
    Pod容器应用"优雅发布"
    Pod容器自动伸缩(HPA) 测试
    NFS双机热备高可用环境
  • 原文地址:https://www.cnblogs.com/chinaxxren/p/3457814.html
Copyright © 2020-2023  润新知