Reputation: 2822
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?
Upvotes: 28
Views: 36482
Reputation: 2687
dispatch_get_global_queue
is kind of concurrency queue.As you specify the same priority for high1 and high2, the result is mix of high1 and high2. After that,it will be the low result as it has a lower priority.
Upvotes: 0
Reputation: 6723
You've just illustrated why you shouldn't call methods that aren't thread-safe inside dispatch_async
. If there are enough processing cores to execute more jobs, GCD will go ahead and pile work on them regardless of whether previous jobs in a given queue have returned yet. The same behaviour can be achieved in OS X 10.7 by creating your own queues with:
dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT);
Obviously NSLog()
can be called as often as you like without worrying about getting bad access errors or similar but if you're concerned about thread-safety or the order in which your jobs return consider using dispatch groups.
Upvotes: 7
Reputation: 16448
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.
Upvotes: 22