Research on iOS multithreading GCD

Source: Internet
Author: User

Grand Central Dispatch (GCD) is a solution for multi-core programming developed by Apple.
The dispatch queue is divided into the following three types:
1) Run the main queue in the main thread, obtained through Dispatch_get_main_queue.

Java code
  1. /*!
  2. * @function Dispatch_get_main_queue
  3. *
  4. * @abstract
  5. * Returns The default queue, which is bound to the main thread.
  6. *
  7. * @discussion
  8. * In order to invoke blocks submitted to the main queue, the application must
  9. * Call Dispatch_main (), Nsapplicationmain (), or use a cfrunloop on the main
  10. * Thread.
  11. *
  12. * @result
  13. * Returns the main queue. This queue was created automatically on behalf of
  14. * The main thread before main () is called.
  15. */
  16. __osx_available_starting (__MAC_10_6,__IPHONE_4_0)
  17. dispatch_export struct dispatch_queue_s _dispatch_main_q;
  18. #define DISPATCH_GET_MAIN_QUEUE () \
  19. Dispatch_global_object (dispatch_queue_t, _dispatch_main_q)
/*!* @function dispatch_get_main_queue** @abstract * Returns The default queue that is  Bound to the main thread.** @discussion * on order to invoke blocks submitted to the main queue, the application must* call Dispatch_main (), Nsapplicationmain (), or use a cfrunloop on the main* thread.** @result * Returns the main queue. This queue was created automatically on behalf of* the main thread before main () is called.*/__osx_available_starting (__mac _10_6,__IPHONE_4_0) dispatch_export struct dispatch_queue_s _dispatch_main_q; #define DISPATCH_GET_MAIN_QUEUE () Dispatch_global_object (dispatch_queue_t, _dispatch_main_q) 

As can be seen, Dispatch_get_main_queue is also a kind of dispatch_queue_t.
2) Parallel queue Global dispatch queue, obtained by Dispatch_get_global_queue, creates three different priority dispatch queues by the system. Parallel queues are executed in the same order as they join the queue.
3) Serial queue serial queues is typically used to synchronize access sequentially, creating any number of serial queues that are concurrent between each serial queue.
Serial queues are useful when you want tasks to execute in a particular order. A serial queue performs only one task at a time. We can use serial queues instead of locks to protect shared data. Unlike locks, a serial queue guarantees that the task executes in a predictable order.
Serial queues is created through dispatch_queue_create and can be used to increase or decrease the reference count using function Dispatch_retain and dispatch_release.
Usage of GCD:

Java code
  1. Background execution:
  2. Dispatch_async (Dispatch_get_global_queue (0, 0), ^{
  3. //Something
  4. });
  5. //Main thread execution:
  6. Dispatch_async (Dispatch_get_main_queue (), ^{
  7. //Something
  8. });
  9. //Disposable Execution:
  10. static dispatch_once_t Oncetoken;
  11. Dispatch_once (&oncetoken, ^{
  12. //code to be executed once
  13. });
  14. //Delay 2 seconds Execution:
  15. Double delayinseconds = 2.0;
  16. dispatch_time_t poptime = Dispatch_time (Dispatch_time_now, delayinseconds * nsec_per_sec);
  17. Dispatch_after (Poptime, Dispatch_get_main_queue (), ^ (void) {
  18. //code to being executed on the main queue after delay
  19. });
  20. //Custom dispatch_queue_t
  21. dispatch_queue_t urls_queue = dispatch_queue_create ("blog.devtang.com", NULL);
  22. Dispatch_async (Urls_queue, ^{
  23. //Your code
  24. });
  25. Dispatch_release (Urls_queue);
  26. //Merge Summary results
  27. dispatch_group_t group = Dispatch_group_create ();
  28. Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{
  29. //parallel execution of thread one
  30. });
  31. Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{
  32. //threads executed in parallel two
  33. });
  34. Dispatch_group_notify (Group, Dispatch_get_global_queue (0,0), ^{
  35. //Summary Results
  36. });
Background execution: Dispatch_async (dispatch_get_global_queue (0, 0), ^{//Something}); Main thread execution: Dispatch_async (Dispatch_get_main_queue (), ^{//Something}); Disposable execution: Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{//code to be executed once}); Delay 2 seconds execution: double delayinseconds = 2.0; dispatch_time_t poptime = Dispatch_time (Dispatch_time_now, delayinseconds * nsec_per_sec); Dispatch_after (Poptime, Dispatch_get_main_queue (), ^ (void) {//code to is executed on the main queue after delay}); Custom dispatch_queue_t dispatch_queue_t urls_queue = dispatch_queue_create ("blog.devtang.com", NULL); Dispatch_async (Urls_queue, ^{//Your code}); Dispatch_release (Urls_queue); Merge Summary results dispatch_group_t group = dispatch_group_create (); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{//parallel execution of thread one}); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{//Parallel execution thread two}); Dispatch_group_notify (Group, Dispatch_get_global_queue (0,0), ^{      Aggregated results}); 

An example of applying GCD:

Java code
  1. Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
  2. Nsurl * url = [nsurl urlwithstring:@"http://www.baidu.com"];
  3. Nserror * ERROR;
  4. NSString * data = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];
  5. if (data! = nil) {
  6. Dispatch_async (Dispatch_get_main_queue (), ^{
  7. NSLog (@"Call back, the data is:%@", data);
  8. });
  9. } Else {
  10. NSLog (@"error when download:%@", error);
  11. }
  12. });
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{        nsurl * url = [NSURL urlwithstring:@ "http://www.baidu.com"];        Nserror * ERROR;        NSString * data = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];        if (data = nil) {            Dispatch_async (Dispatch_get_main_queue (), ^{                NSLog (@ "Call back, the data is:%@", data);            } );        } else {            NSLog (@ "error when download:%@", error);        }    );

Another use of GCD is to allow programs to run longer in the background.
When you do not use GCD, when the app is left on the home button, the app only has a maximum of 5 seconds to do some saving or cleanup work. But after using GCD, the app has a maximum of 10 minutes to run in the background for a long time. This time can be used to clean up the local cache, send statistics and other work.
The sample code that lets the program run long in the background is as follows:

Java code
  1. AppDelegate.h file
  2. @property (Assign, nonatomic) Uibackgroundtaskidentifier backgroundupdatetask;
  3. APPDELEGATE.M file
  4. -(void) Applicationdidenterbackground: (uiapplication *) Application
  5. {
  6. [Self beingbackgroundupdatetask];
  7. //Add the code you need to run long
  8. [Self endbackgroundupdatetask];
  9. }
  10. -(void) Beingbackgroundupdatetask
  11. {
  12. Self.backgroundupdatetask = [[UIApplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{
  13. [Self endbackgroundupdatetask];
  14. }];
  15. }
  16. -(void) Endbackgroundupdatetask
  17. {
  18. [[UIApplication sharedapplication] endBackgroundTask:self.backgroundUpdateTask];
  19. Self.backgroundupdatetask = Uibackgroundtaskinvalid;
  20. }

Research on iOS multithreading GCD

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.