The following code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
for (int i=0; i<100000; i++) {
NSLog(@"HIGH 1 %d", i);
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
for (int i=0; i<100000; i++) {
NSLog(@"LOW %d", i);
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
for (int i=0; i<100000; i++) {
NSLog(@"HIGH 2 %d", i);
}
});
results in mixture of high 1, high 2 and low logs.
How is it that it prints high1 and high2 logs simultaneously. aren't both high1 and high2 blogs on the same queue? So shouldn't high1 block finish before starting to execute high2 block?
That depends on the machine you're running on. I suspect you're running this on your Mac, because GCD will automatically create enough threads for the specific system for jobs on the global queues. So, you probably have more than one core, so GCD is running your jobs on both the cores.
If you create your queue using dispatch_queue_create
, you get a serial queue, and you are then guaranteed FIFO behaviour.
FWIW (although you shouldn't rely on this behaviour), if you run that on the iPhone, I suspect you'll see serial queue behaviour, because your iPhone is single-core. Don't rely on this though, the iPad 2 is multi-core I think!
EDIT:
Documentation for dispatch_get_global_queue
:
Returns a well-known global concurrent queue of a given priority level.