iphone - What will happen if I have nested dispatch_async calls? -
it may dumb question need ask , clear myself.
to submit block onto queue execution, use functions dispatch_sync
, dispatch_async
. both take queue , block parameters. dispatch_async
returns immediately, running block asynchronously, while dispatch_sync
blocks execution until provided block returns. here situations:
situation 1
dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0ul); dispatch_async(queue, ^{ [self godosomethinglongandinvolved]; dispatch_async(queue, ^{ nslog(@"this statement1"); }); });
situation 2
dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0ul); dispatch_sync(queue, ^{ [self godosomethinglongandinvolved]; dispatch_sync(queue, ^{ nslog(@"this statement1"); }); });
situation 3
{ [super viewdidload]; dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0ul); dispatch_async(queue, ^{ [self godosomethinglongandinvolved]; dispatch_sync(queue, ^{ nslog(@"this statement1"); }); });
situation 4
{ [super viewdidload]; dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0ul); dispatch_sync(queue, ^{ [self godosomethinglongandinvolved]; dispatch_async(queue, ^{ nslog(@"this statement1"); }); });
}
and godosomethinglongandinvolved
is
-(void)godosomethinglongandinvolved { nslog(@"godosomethinglongandinvolved"); }
i tried run them in xcode cant see difference @ all.
so questions are:
- what's main difference between these situations?
- what if replace
queue
dispatch_get_main_queue()
?
the dispatch_sync
statement waits until block covers executed completely. dispatch_async
returns , proceeds next line of code, inside happening in parallel.
if queue
serial queue created yourself, then:
situation 1 - root block returns immediately. inside waits [self go....], , goes dispatch_async, returns well.
situation 2 - if queue
serial queue, there dead lock since wait finish executing. since dealing asynchronous one, block executed in parallel. (thanks, @ken thomases)
situation 3 - no need in dispatch_sync
here. causes deadlock.
situation 4 - waits [self ...], returns immediately.
if replace queue
main queue, remember not dispatch_sync
on main queue, because cause deadlock (it not if dispatched not main thread, @ken thomases).
to understand better, replace function with:
-(void)godosomethinglongandinvolved:(nsstring *)message { for(int = 0; < 50; ++i) { nslog(@"%@ -> %d", message, i); } }
you see what's going on every time, whether waits or not. luck.
Comments
Post a Comment