ios - dispatch_sync inside dispatch_sync causes deadlock -


i read on objc.io going asynchronous can't find explanation

dispatch_queue_t queuea; // assume have dispatch_sync(queuea, ^(){  // (a)     dispatch_sync(queuea, ^(){ // (b)         foo();     }); }); 

once hit second dispatch_sync we’ll deadlock: can’t dispatch onto queuea, because (the current thread) on queue , never going leave it.

as long understand

  1. dispatch_sync add work item (i avoid using word "block" may confuse) queuea, work item send queuea 's target queue, gcd preserve thread threadworkitem work item
  2. when reach (b), i'm in thread threadworkitem (suppose threadworkitem name of thread), think enqueuing work item queuea no problem. people @ time, queuea preserved, queuea blocked -> causes deadlock, confuses me

i read many threads related this, such deadlock dispatch_sync, why can't use dispatch_sync on current queue?, why dispatch_sync() call freezing?, ... can't find explanation. dispatch_sync blocks queue, blocks current thread, ... :(

so why cause deadlock ?

the dispatch_sync blocks current thread until dispatched code finishes, , if you're dispatching synchronously serial queue, therefore blocking queue, too. if synchronously dispatch serial queue itself, results in deadlock.

but clear, dispatch_sync blocks current thread, not current queue. when dealing concurrent queue, different worker thread used subsequently dispatched block , no deadlock results.

you appear responding discussion @ end of dispatch queues chapter of concurrency programming guide, says:

do not call dispatch_sync function task executing on same queue pass function call. doing deadlock queue. if need dispatch current queue, asynchronously using dispatch_async function.

that not entirely correct. if (a) doing concurrent queue; , (b) there available worker threads, not cause deadlock. it's bad practice , should avoided, nonetheless.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -