一、简介
dispatch_group_enter:通知group,下面的任务马上要放到group中执行了。
dispatch_group_leave:通知group,任务完成了,该任务要从group中移除了。
这两种通知可以在多线程间自由穿梭的。
二、验证
下面用代码验证下它们的作用。
-
(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self syncAction];
} -
(void)syncAction{
dispatch_group_t group =dispatch_group_create();
dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
dispatch_group_enter(group);
//模拟多线程耗时操作
dispatch_group_async(group, globalQueue, ^{
sleep(3);
NSLog(@"%@---block1结束。。。",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@---1结束。。。",[NSThread currentThread]);
dispatch_group_enter(group);
//模拟多线程耗时操作
dispatch_group_async(group, globalQueue, ^{
sleep(3);
NSLog(@"%@---block2结束。。。",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@---2结束。。。",[NSThread currentThread]);
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"%@---全部结束。。。",[NSThread currentThread]);
});
}
2016-12-23 09:46:27.853 CPMNetworking[1341:36092] <NSThread: 0x600000068600>{number = 1, name = main}---1结束。。。
2016-12-23 09:46:27.856 CPMNetworking[1341:36092] <NSThread: 0x600000068600>{number = 1, name = main}---2结束。。。
2016-12-23 09:46:30.923 CPMNetworking[1341:36550] <NSThread: 0x608000263f00>{number = 4, name = (null)}---block1结束。。。
2016-12-23 09:46:30.930 CPMNetworking[1341:36176] <NSThread: 0x6000002647c0>{number = 5, name = (null)}---block2结束。。。
2016-12-23 09:46:30.930 CPMNetworking[1341:36176] <NSThread: 0x6000002647c0>{number = 5, name = (null)}---全部结束。。。
网友评论