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?
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.
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.
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.
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.
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).
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