Explain the use of iOS multithreading GCD

  • 2020-05-19 05:57:21
  • OfStack

Grand Central Dispatch (GCD) is one of the techniques for performing tasks asynchronously

dispatch queue falls into the following three categories:

1) Main queue running on the main thread is obtained through dispatch_get_main_queue.


/*!
* @function dispatch_get_main_queue
*
* @abstract
* Returns the default queue that is bound to the main thread.
*
* @discussion
* In 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 is 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)

It can be seen that dispatch_get_main_queue is also a kind of dispatch_queue_t.

2) parallel queue global dispatch queue is obtained through dispatch_get_global_queue, and three dispatch queue with different priority are created by the system. Parallel queues are executed in the same order as they were queued.

3) serial queue serial queues1 is generally used for sequential synchronous access. Any number of serial queues can be created, and each serial queue is concurrent.

Serial queues are useful when you want tasks to be executed in a particular order. The serial queue executes only one task at the same time. We can use serial queues instead of locks to protect Shared data. Unlike locks, a serial queue ensures that tasks are executed in a predictable order.

serial queues is created by dispatch_queue_create, and you can use the functions dispatch_retain and dispatch_release to increase or decrease the reference count.

Usage of GCD:


 //  Background execution: 
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
  // something
 });

 //  Main thread execution: 
 dispatch_async(dispatch_get_main_queue(), ^{
  // something
 });

 // 1 Secondary execution: 
 static dispatch_once_t onceToken;
 dispatch_once(&onceToken, ^{
  // code to be executed once
 });

 //  delay 2 Seconds to perform: 
 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 be executed on the main queue after delay
 });

 //  The 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);

 //  Combined results 
 dispatch_group_t group = dispatch_group_create();
 dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
  //  Threads that execute in parallel 1
 });
 dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
  //  Threads that execute in parallel 2
 });
 dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
  //  Summary results 
 });

An example of using GCD:


 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 keep programs running in the background for a long time.

When GCD is not used, when app is pressed home to exit, app has only a maximum of 5 seconds to save or clean up the resource. But after using GCD, app has up to 10 minutes to run long in the background. This time can be used to clean up the local cache, send statistics, and so on.

Here's an example of how to make a program run long in the background:


// AppDelegate.h file 
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m file 
- (void)applicationDidEnterBackground:(UIApplication *)application
{
 [self beingBackgroundUpdateTask];
 //  Add in the code that you need to run for a long time 
 [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask
{
 self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  [self endBackgroundUpdateTask];
 }];
}

- (void)endBackgroundUpdateTask
{
 [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
 self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

The above content is the IOS in GCD that this site introduces to you, hope to help you!


Related articles: