我正在尝试了解 iOS GCD 的并发队列。我做了一些代码来测试它,但发现了一些奇怪的东西。代码如下:
_syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
for (int index = 0; index < 3; ++index) {
dispatch_sync(_syncQueue, ^{
NSLog(@"sync@@@@@@ >>>> %d ",index);
sleep(1);
NSLog(@"sync@@@@@@ <<<< %d ",index);
});
}
for (int index = 3; index < 6; ++index) {
dispatch_async(_syncQueue, ^{
NSLog(@"sync===== >>>> %d ",index);
sleep(1);
NSLog(@"sync===== <<<< %d ",index);
});
}
for (int index = 6; index < 9; ++index) {
dispatch_sync(_syncQueue, ^{
NSLog(@"sync***** >>>> %d ",index);
sleep(1);
NSLog(@"sync***** <<<< %d ",index);
});
}
执行结果如下:
sync@@@@@@ >>>> 0
sync@@@@@@ <<<< 0
sync@@@@@@ >>>> 1
sync@@@@@@ <<<< 1
sync@@@@@@ >>>> 2
sync@@@@@@ <<<< 2
sync***** >>>> 6
sync===== >>>> 4
sync===== >>>> 3
sync===== >>>> 5
sync***** <<<< 6
sync***** >>>> 7
sync===== <<<< 4
sync===== <<<< 5
sync===== <<<< 3
sync***** <<<< 7
sync***** >>>> 8
sync***** <<<< 8
我很困惑,无法理解为什么它会这样运行。
为什么直到第一个循环运行完全完成然后第二个和第三个循环才能开始运行,对我来说,第一个循环至少应该被第二个循环中断,因为第二个循环可以创建新的线程来执行。
为什么第三个循环比第二个循环更早开始?
为什么第三个循环不能作为第一个循环运行而不会被其他任务中断?