The difference between GCD multithreading-dispatch_async and Dispatch_sync

Source: Internet
Author: User

From the literal distinction between async and sync, async is the asynchronous abbreviation, and sync is the abbreviation for synchronization.

1, dispatch_async means asynchronous processing, the main program does not wait for block blocks to execute the results.

int Main (intconstChar * argv[]) {    = dispatch_get_main_queue ();    ^{        NSLog (@ "+++++++");});    NSLog (@ "hahahaha");     return 0 ;}

Output Result: hahahaha

No output +++++++ in results

Result Analysis : Asynchronous execution does not affect the execution of the main thread, and the block is added to the main queue at the end. But because it runs directly to the return line, the main thread is killed and the block blocks added to the main thread are not executed. If you are in an app project, you will first output hahahaha and then output +++++++.

2, dispatch_sync means that synchronous processing, the main program must wait until block blocks are executed, can continue to execute down.

    dispatch_queue_t Queuemain = dispatch_get_main_queue ();     ^{        NSLog (@ "+++++++");});    NSLog (@ "hahahaha");

The program stops at the Dispatch_sync () line.

result Analysis : Because the main thread executes to Dispatch_sync (), it is in a wait state. Add the block block to the main queue and wait for the current Mian thread to execute the block block after the task has finished executing. Cause both sides are waiting, so there is a deadlock, the program stuck.

GCD multithreading-dispatch_async differs from Dispatch_sync

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.