简体   繁体   中英

Multiple GCD Dispatches on main thread

I'm trying to speed up the boot of my app, and one of the ideas i had for that was to use asynchronous dispatch queues. I have 2 tasks that can be run next to each other at startup (quite big tasks actually). However, both of them have a significant part that runs on the main thread (UI code mainly).

dispatch_async(dispatch_get_main_queue, ^{
    [self doTask1];
});

dispatch_async(dispatch_get_main_queue, ^{
    [self doTask2];
    //Will task 2 take turns with task 1, or will task 2 start after 1 is finished?
});

My question is this: If i call 2 dispatch_async's at boot like in this example, will they take turns in executing, or will the complete first block execute first, then the 2nd block?

the main queue is a serial queue. blocks added to serial queues are executed in the order they are added and only one at a time (serially). in your example, task2 will not start until task1 has finished.

if you want them to run concurrently you'll need to dispatch them to one of the global concurrent queues.

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(q, ^{/* this work may finish before other work added to this queue later */});

One will be executed after the other, but they will execute concurrently, meaning you can execute task2 before task1 has finished.

Check the alternative:

dispatch_async(dispatch_get_main_queue, ^{
    [self doTask1];
    dispatch_async(dispatch_get_main_queue, ^{
        [self doTask2];
        //Now task2 will execute after task1
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM