//
// ViewController.m
// test_dispatch_assync_barry_01
//
// Created by jeffasd on 17/4/26.
// Copyright © 2017年 jeffasd. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{
int _count;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_count = 0;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self testDispatchBarrierAsync];
}
- (void)testDispatchBarrierAsync{
if (_count >= 100) {
return;
}
NSLog(@"----------------------------");
dispatch_queue_t concurrentQueue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^(){
NSLog(@"dispatch-1");
});
dispatch_async(concurrentQueue, ^(){
NSLog(@"dispatch-2");
});
dispatch_barrier_async(concurrentQueue, ^(){
NSLog(@"dispatch-barrier");
});
dispatch_async(concurrentQueue, ^(){
NSLog(@"dispatch-3");
});
dispatch_async(concurrentQueue, ^(){
NSLog(@"dispatch-4");
});
_count++;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self testDispatchBarrierAsync];
});
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
2017-04-26 13:55:02.117 test_dispatch_assync_barry_01[9348:1159895] ----------------------------
2017-04-26 13:55:02.118 test_dispatch_assync_barry_01[9348:1159979] dispatch-2
2017-04-26 13:55:02.118 test_dispatch_assync_barry_01[9348:1159981] dispatch-1
2017-04-26 13:55:02.118 test_dispatch_assync_barry_01[9348:1159981] dispatch-barrier
2017-04-26 13:55:02.118 test_dispatch_assync_barry_01[9348:1159981] dispatch-3
2017-04-26 13:55:02.118 test_dispatch_assync_barry_01[9348:1159979] dispatch-4
2017-04-26 13:55:11.200 test_dispatch_assync_barry_01[9348:1159895] ----------------------------
2017-04-26 13:55:11.200 test_dispatch_assync_barry_01[9348:1159981] dispatch-1
2017-04-26 13:55:11.200 test_dispatch_assync_barry_01[9348:1159979] dispatch-2
2017-04-26 13:55:11.201 test_dispatch_assync_barry_01[9348:1159979] dispatch-barrier
2017-04-26 13:55:11.201 test_dispatch_assync_barry_01[9348:1159981] dispatch-4
2017-04-26 13:55:11.201 test_dispatch_assync_barry_01[9348:1159979] dispatch-3
dispatch_barrier_async 作用是在并行队列中,等待前面两个操作并行操作完成,这里是并行输出
dispatch-1,dispatch-2
然后执行
dispatch_barrier_async中的操作,(现在就只会执行这一个操作)执行完成后,即输出
"dispatch-barrier,
最后该并行队列恢复原有执行状态,继续并行执行
dispatch-3,dispatch-4
可以看出来 1和2的执行是没有先后顺序的,3和4也没有先后顺序 但是
dispatch-barrier 肯定是在 12 结束后43是在dispatch-barrier结束后执行
参考文章:
http://www.cnblogs.com/zhidao-chen/p/3598161.html