博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
dispatch_group_t
阅读量:7056 次
发布时间:2019-06-28

本文共 1592 字,大约阅读时间需要 5 分钟。

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被打印。

转载于:https://www.cnblogs.com/chinaxxren/p/3457814.html

你可能感兴趣的文章
变量提升
查看>>
读写文件
查看>>
Spring Tool Suite (STS)使用Spring Template Project 生成项目时报错解决方法
查看>>
apache性能优化
查看>>
apache伪静态设置
查看>>
MathType手写输入面板清空的方法
查看>>
专注Jquery
查看>>
CSS之flex兼容
查看>>
《APUE》读书笔记—第四章文件和目录
查看>>
10分钟精通SharePoint - SharePoint定位
查看>>
密码应用技术系列之0:开篇
查看>>
cat、head、tail、more和less命令(文件内容浏览)
查看>>
SpringMVC (八)SpringMVC返回值类型
查看>>
poj1190生日蛋糕--DFS
查看>>
多线程-synchronized
查看>>
2018.03.28
查看>>
cc笔记_web测试方法总结
查看>>
Exchange企业实战技巧(18)日志规则应用之审计邮箱
查看>>
sharepoint 2010 同步问题
查看>>
iftop流量监控使用
查看>>