Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_get_global_queue behaviour

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?

like image 517
Ashish Awaghad Avatar asked Jul 29 '11 11:07

Ashish Awaghad


People also ask

What is Dispatch_get_global_queue?

Returns a system-defined global concurrent queue with the specified quality-of-service class.

Does Dispatch_async create a thread?

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.


1 Answers

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.

like image 66
joerick Avatar answered Sep 22 '22 03:09

joerick