Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What behavior is guaranteed with Grand Central Dispatch in Objective-C?

I think the best way to ask this question is with some code:

//Main method
for(int i = 0; i < 10; i++)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
         [self foo:i];
    });

}

- (void) foo: (int) i
{
    @synchronized(self)
    {
        NSLog(@"%d",i);
    }
}

In this case, is it guaranteed that the numbers 0-9 will be printed out in order? Is there ever a chance that one of the threads that is waiting on the run queue, will be skipped over? How about in reality. Realistically, does that ever happen? What if I wanted the behavior above (still using threads); how could I accomplish this?

like image 942
Nosrettap Avatar asked Apr 08 '13 15:04

Nosrettap


People also ask

How does Grand Central Dispatch work?

GCD is built on top of threads. Under the hood, it manages a shared thread pool. With GCD, you add blocks of code or work items to dispatch queues and GCD decides which thread to execute them on. As you structure your code, you'll find code blocks that can run simultaneously and some that should not.

What is Grand Central Dispatch in iOS?

Dispatch, also known as Grand Central Dispatch (GCD), contains language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in macOS, iOS, watchOS, and tvOS.

What is the use of dispatch queue in Swift?

A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. A dispatch queue that executes tasks concurrently using threads from the global thread pool.

Is global queue serial or concurrent?

Concurrent queues (also known as a type of global dispatch queue) execute one or more tasks concurrently, but tasks are still started in the order in which they were added to the queue.


1 Answers

In this case, is it guaranteed that the numbers 0-9 will be printed out in order?

No.

Is there ever a chance that one of the threads that is waiting on the run queue, will be skipped over?

Unclear what "skipped over" means. If it means "will the blocks be executed in order?" the answer is "probably, but it is an implementation detail".

How about in reality. Realistically, does that ever happen?

Irrelevant. If you you are writing concurrency code based on assumptions about realistic implementation details, you are writing incorrect concurrency code.

What if I wanted the behavior above (still using threads); how could I accomplish this?

Create a serial dispatch queue and dispatch to that queue in the order you need things to be executed. Note that this is significantly faster than @synchronized() (of course, @synchronized() wouldn't work for you anyway in that it doesn't guarantee order, but merely exclusivity).

like image 195
bbum Avatar answered Sep 28 '22 07:09

bbum