Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How queues and threading work?

This is related to the Grand Central Dispatch API used in objective-c, with the following codes:

dispatch_queue_t downloadQueue = dispatch_queue_create("other queue", NULL);
dispatch_async(downloadQueue, ^{
    ....some functions that retrieves data from server...
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"got it");
    });
});
dispatch_release(downloadQueue);

My current understanding of how queues work is that the blocks in a queue will go on a thread for that queue. So two queues will become two threads. With multi-threading, those two queues will happen simultaneously. However, the "got it" appears right at when the program received the data. How did that happen?

Please point out if you want to correct or add to my understanding of threading and queue.

like image 509
William Sham Avatar asked Jul 26 '26 17:07

William Sham


1 Answers

So two queues will become two threads.

Not necessarily. One of the advantages of GCD is that the system dynamically decides how many threads it creates, depending on the number of available CPU cores and other factors. It might well be that two custom queues are executed on the same background thread, especially if there are rarely tasks for both queues waiting to be executed.

The only thing you can be certain about is that a serial queue never uses more than one thread at the same time. So the tasks you add to the same (serial) queue will always be executed in order. This is not the case for the three concurrent global queues you get with dispatch_get_global_queue().

Additionally, the main queue (the one you access with dispatch_get_main_queue()) is always bound to the main thread. It is the only queue whose tasks are executed on the program's main thread.

In your example, the task for the downloadQueue gets executed on a background thread. As soon as the code reaches dispatch_async(dispatch_get_main_queue(), ^{, GCD pushes this new task to the main thread where it gets executed practically immediately provided that the main thread is not busy with other things.

like image 93
Ole Begemann Avatar answered Jul 28 '26 10:07

Ole Begemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!