int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"--------------------------");
dispatch_queue_t queue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"01");
dispatch_sync(queue, ^(){
NSLog(@"02");
[NSThread sleepForTimeInterval:3];
NSLog(@"03");
});
NSLog(@"04");
NSLog(@"--------------------------");
queue = dispatch_queue_create("my.concurrent.queue",
DISPATCH_QUEUE_CONCURRENT);
NSLog(@"11");
dispatch_async(queue, ^(){
NSLog(@"12");
[NSThread sleepForTimeInterval:5];
NSLog(@"13");
});
NSLog(@"14");
[NSThread sleepForTimeInterval:6];
}
return 0;
}
结果:
2016-11-27 22:23:01.132 dispatchTest[505:6126] --------------------------
2016-11-27 22:23:01.134 dispatchTest[505:6126] 01
2016-11-27 22:23:01.134 dispatchTest[505:6126] 02
2016-11-27 22:23:04.144 dispatchTest[505:6126] 03
2016-11-27 22:23:04.144 dispatchTest[505:6126] 04
2016-11-27 22:23:04.145 dispatchTest[505:6126] --------------------------
2016-11-27 22:23:04.145 dispatchTest[505:6126] 11
2016-11-27 22:23:04.147 dispatchTest[505:6126] 14
2016-11-27 22:23:04.147 dispatchTest[505:6156] 12
2016-11-27 22:23:09.153 dispatchTest[505:6156] 13
Program ended with exit code: 0
本文通过具体的代码示例,展示了如何使用 GCD (Grand Central Dispatch) 在 macOS 系统下创建并发队列,并分别采用同步和异步的方式执行任务。通过对输出结果的观察,可以了解到不同调度方式对任务执行顺序的影响。
1058

被折叠的 条评论
为什么被折叠?



