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?
Returns a system-defined global concurrent queue with the specified quality-of-service class.
When using dispatch_async for a background queue, GCD (Grand Central Dispatch) will ask the kernel for a thread, where the kernel either creates one, picks an idle thread, or waits for one to become idle. These threads, once created, live in the thread pool.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With