iOS dispatch_sync(dispatch_get_main_queue()、^ {});デッドロックを引き起こす



Ios Dispatch_sync



- (void)viewDidLoad { dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@1) // deadlock reasons // 1: dispatch_sync wait block statement is executed at the completion of, and block statements to execute on the main thread, so dispatch_sync if it will cause a deadlock in the main thread calls // 2: dispatch_sync is synchronized itself will block the current thread, that is the main thread. But the main thread to go into a block, so a deadlock occurs. }) dispatch_async(dispatch_get_global_queue(), ^{ // async created in the main thread of an asynchronous thread to join global concurrent queue, async not wait block execution is complete, return immediately NSLog (@ 2) // not cause a deadlock }) }

このコードの分析:

メインスレッドのviewDidLoad、つまり、dispatch_get_main_queue()、execute()を実行して、同期の場合、dispatch_get_main_queueスレッドを挿入します。 。内部のメインキューで再度同期します。これはシリアルキューであり、同期は後でメインスレッドの前に追加されるだけなので、メインスレッドがフォローアップを実行するために同期を待機して戻ったため、デッドロックが発生しました。



dispatch_syncとdispatch_asyncの違い:

dispatch_async(queue、block)async非同期キュー、dispatch_async関数はすぐに戻り、ブロックはバックグラウンドで非同期に実行されます。
dispatch_sync(queue、block)sync同期キューdispatch_sync関数はすぐには返されません。これは現在のスレッドをブロックし、同期ブロックの実行が完了するのを待ちます。



3つのキューに分割されたGCDキュー:

シリアルキュー:ディスパッチキューまたはシリアルキュー
並行キュー:並行キュー
メインキュー:メインディスパッチキュー