iOS Learning GCD

Source: Internet
Author: User
Tags gcd fully qualified domain name

Multithreaded programming

thread definition: A CPU-executed CPU command column A non-bifurcated path is called a thread .

Multithreading: There are multiple paths to executing several different CPU commands .

Threading Usage: The primary thread (also called the UI thread) is to handle UI events, display and refresh the UI (only the main thread has the ability to directly modify the UI), and the time-consuming operations are placed on child threads (also called background threads, asynchronous threads).

Multithreading is prone to programming problems:

    1. data contention: multiple threads updating the same resource can result in inconsistent data .
    2. deadlock: a thread that stops waiting for an event causes multiple threads to continue waiting for each other .
    3. Too many threads consume a lot of memory .
    4. Thread Safe (thread-safe): A thread-safe code (object) that can be dispatched by multiple threads or concurrent tasks at the same time, without problems, and non-thread-safe can only be accessed in order.

Multithreading Advantages: in the need to often actual processing methods placed in other threads, let other threads processing, the main thread does not process .

in the GCD Previous multithreading methods : Nsthread, Nsoperationqueue, nsinvocationoperation

Gcd:grand Central Dispatch: Techniques for performing tasks asynchronously.

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.

Method advantages and Disadvantages Analysis:

    1. Nsthread ( abstract level: Low )
    • Pros: Lightweight, easy to use, can manipulate thread objects directly
    • Cons: You need to manage your thread's life cycle, thread synchronization. Thread synchronization has a certain overhead in locking data.
    1. Cocoa nsoperation ( abstract level: Medium )
    • Pros: Do not need to care about thread management, data synchronization, you can focus on learning to perform the operation. Based on GCD, is the encapsulation of GCD, more object-oriented than GCD
    • Cons: Nsoperation is an abstract class that uses its subclasses to implement it or to use its defined two subclasses, Nsinvocationoperation, Nsblockoperation.
    1. GCD level of abstraction: High )
    • Pros: A multi-core programming solution developed by Apple that is easy to use, efficient, fast, based on C, more efficient at the bottom, and not part of the cocoa framework that automatically manages the thread lifecycle (creating threads, scheduling tasks, destroying threads).
    • Cons: If you're using a GCD scenario, there's a very large likelihood of a deadlock problem.

GCD The advantages

    1. GCD is Apple's solution for multi-core parallel computing
    2. GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core)
    3. GCD automatically manages the life cycle of threads (create threads, schedule tasks, destroy threads)
    4. Programmers just need to tell gcd what tasks they want to perform, without having to write any thread management code

Prior to GCD, the cocoa framework provided performselectorinbackgroud:withobject instance methods and Performselectoronmainthread instance methods for NSObject classes.

    • Performselector can easily be negligent in memory management, it cannot determine what the selector is going to do, so arc has no way of inserting an appropriate memory management method

SEL selector;

If () {

[Email protected] Selector (NewObject)}

Else if () {
[Email protected] Selector (copy)}

Else {
[Email protected] Selector (SOMESASR)}

Id ret=[object performselector:selector//So the compiler does not know which seletor is to be executed, it must be run to determine, arc is not able to insert the appropriate memory management method. An error warning will appear.

];

The first two need to release themselves, the latter do not need to release themselves, the use of Arc error warning, do not use arc easy to ignore, even if using static analysis of it, it is difficult to detect

    • The handling of things is too restrictive, the return value type and the number of parameters sent to the method are limited.
    • If you want to put the task on another thread, it is best not to use the Performselector method, should be encapsulated in the block, and then call GCD to implement.

Performselector and GCD deal with the same task:

1) [Self performselector: @selector (dosomething)

Withobject:nil

after:5.0];//Performselector

2) dispatch_time_t Time=dispatch_time (Dispatch_time_now,

(int64_t) (5.0*nsec_per_sec));

Dispatch_after (Time,dispatch_get_main_queue (), ^ (void) {
[Self dosomething];});//gcd

Dispatch methods provided by the system:

    1. Background execution:

Dispatch_async (Dispatch_get_global_queue (0,0), ^{

Something

});

    1. Main thread Execution:

Dispatch_async (Dispatch_get_main_queue (), ^{

Something

});

    1. One-time execution: Dispatch_once ensure that code in the block executes only once during the app run
    • Classic usage Scenarios---single case
    • The definition of a singleton object Sharemanager:

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

Something

});

    1. Delay of 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) {

Oncetoken

});

    1. Custom execution:

To customize a queue you can use Dispatch_queue_create

Xiang Gcd's API

Note: Simply add the task you want to perform to the appropriate dispatch queue.

two kinds of Dispatch queue:(Concurrent Dispatch queue)

   

    1. Serial the Dispatch queue serial queue (Figure 1): Let the task execute one after the other (after a task is completed, the next task is executed)

Serial Dispatch queue too much can easily consume too much memory.

So use serial Dispatch Queue only when possible data is competing.

    1. Concurrent Dispatch Queue concurrent queues (Figure 2): Do not wait for the current execution to end (you can have multiple tasks concurrently (and concurrently) execute (automatically open multiple threads concurrently to perform the task) concurrency function only in asynchronous (Dispatch_ Async) function, a thread can handle multiple tasks at the same time. Available when data contention does not occur.
      1. Dispatch_queue_create
    • Features: Creating custom Queues
    • method of Use:dispatch_queue_t dispatch_queue_create (const char *label, dispatch_queue_attr_t attr); Queue name, queue property, general null

dispatch_queue_t myqueue =dispatch_queue_create (com.expample.www,dispatch_queue_concurrent);

Release: Dispatch_release (Myqueue);

    • Note: queue names are recommended using the reverse full domain name of the application ID (fqdn,fully qualified domain name) such as: com.expample.www

Because the queue name is used in the debugger for Xcode and instruments, the dispatch. Easy to find.

The pairs created by the dispatch queue are freed using dispatch_release when the end is used.

      1. Main Dispatch Queue/global Dispatch Queue
    1. The Main Dispatch queue belongs to the serial Dispatch queue type.
    2. The Global Dispatch queue belongs to the Concurrent Dispatch queue type with four priority levels: high priority, default priority, Low priority), Background priorities (background priority)
      1. Dispatch_after
    • function: Let the task delay add to the queue, a block after a specific delay, added to the specified queue, not at a specific time immediately after the run
    • How to use:
      • dispatch_time_t DelayTime3 = Dispatch_time (Dispatch_time_now, 3*nsec_per_sec);
      • dispatch_time_t delayTime2 = Dispatch_time (Dispatch_time_now, 2*nsec_per_sec);
      • dispatch_queue_t mainqueue = Dispatch_get_main_queue ();
      • NSLog (@ "current task");
      • Dispatch_after (DelayTime3, Mainqueue, ^{
      • NSLog (@ "Add to queue after 10 seconds");
      • });
      • Dispatch_after (DelayTime2, Mainqueue, ^{
      • NSLog (@ "Add to queue after 2 seconds");
      • });
      • NSLog (@ "next task");

Output Result:

      • 2015-11-19 15:50:19.369 whisper[2725:172593] Current task
      • 2015-11-19 15:50:19.370 whisper[2725:172593] Next task
      • 2015-11-19 15:50:21.369 whisper[2725:172593] added to queue after 2 seconds
      • 2015-11-19 15:50:29.654 whisper[2725:172593] added to queue after 3 seconds
    • Note:Dispatch_after only delays the submission of block, not immediately after delay execution

      1. dispatch_time_t
    • Function: Create delay time

method of Use:dispatch_time_t dispatch_time (dispatch_time_t when, int64_t Delta);

The first parameter is generally dispatch_time_now, which means starting from now.

Then the second parameter is the exact time of the real delay. The Delta parameter is " nanosecond !"

      • dispatch_time_t DelayTime3 = Dispatch_time (Dispatch_time_now, 3*nsec_per_sec);

Note: The delay of 1 seconds can be written as follows:

Dispatch_time (Dispatch_time_now, 1 * nsec_per_sec);

Dispatch_time (Dispatch_time_now, usec_per_sec);

Dispatch_time (Dispatch_time_now, usec_per_sec * nsec_per_usec);

The last "usec_per_sec * nsec_per_usec" translates to "milliseconds per second multiplied by nanoseconds per millisecond ", which is " nanosecond per second ", so the delay is 500 milliseconds.

    • Nsec_per_sec, how many nanoseconds per second.
    • Usec_per_sec, how many milliseconds per second. (Note is on the basis of nanosecond)
    • Nsec_per_usec, how many nanoseconds per millisecond.
      1. Dispatch Group: Dispatch_group_async
    • function: When you encounter the need to execute multiple threads concurrently, and then wait for multiple threads to end, and then summarize the execution results, you can use the group queue (download multiple pictures at the same time, All pictures are downloaded to update the UI (need to go back to the main thread) or to handle other tasks (which can be other thread queues). )
    • How to use:
    • dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
    • dispatch_group_t group = Dispatch_group_create ();
    • Dispatch_group_async (group, queue, ^{
    • [Nsthread sleepfortimeinterval:1];
    • NSLog (@ "Picture1 download Complete");
    • });
    • Dispatch_group_async (group, queue, ^{
    • [Nsthread Sleepfortimeinterval:2];
    • NSLog (@ "Picture2 download Complete");
    • });
    • Dispatch_group_async (group, queue, ^{
    • [Nsthread Sleepfortimeinterval:3];
    • NSLog (@ "picture3 download Complete");
    • });
    • Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{
    • NSLog (@ "Update Ui");
    • });
    • Dispatch_release (group);

Operational Ideas: use the function dispatch_group_create to create the dispatch group, and then use the function Dispatch_group_async to submit the block task to be executed to a dispatch Queue Add them to a group at the same time, and wait until all the block tasks are completed (three pictures are downloaded), use the Dispatch_group_notify function to receive the completed message (back to the main thread: Update UI).

Operation Result:

16:04:16.737 gcdtest[43328:11303] Picture1 Download complete
16:04:17.738 gcdtest[43328:12a1b] Picture2 Download complete
16:04:18.738 gcdtest[43328:13003] Picture3 Download complete
16:04:18.739 gcdtest[43328:f803] Update Ui

    • Note the point:
      1. Dispatch_barrier_async :
  • function: It executes after the execution of the task in front of it, and the task behind it executes after it finishes executing
  • How to use:
    1. Dispatch_async (Queue, ^{
    2. [Nsthread Sleepfortimeinterval:2];
    3. NSLog (@ "dispatch_async1");
    4. }); First queue
    5. Dispatch_async (Queue, ^{
    6. [Nsthread Sleepfortimeinterval:4];
    7. NSLog (@ "DISPATCH_ASYNC2");
    8. }); A second queue
    9. Dispatch_barrier_async (Queue, ^{
    10. NSLog (@ "Dispatch_barrier_async");
    11. [Nsthread Sleepfortimeinterval:4];
    12. }); Barrier queue
    13. Dispatch_async (Queue, ^{
    14. [Nsthread sleepfortimeinterval:1];
    15. NSLog (@ "dispatch_async3");
    16. }); Fourth queue

Operation Idea: 12th block at the same time, wait for one or two blocks to run the barrier queue, after the barrier queue runs, run the fourth block

Run Result: 16:20:31 start

16:20: - . 967 gcdtest[45547:11203] Dispatch_async1

16:20: * . 967 gcdtest[45547:11303] Dispatch_async2

16:20: * . 967 gcdtest[45547:11303] Dispatch_barrier_async

16:20: + . 970 gcdtest[45547:11303] dispatch_async3

    • Note the point:
      1. Dispatch_sync
    • Function:
    • How to use:
    • Note the point:
      1. Dispatch_apply
  • function: commit a task to the queue more than once, the queue can be serial or parallel, Dispatch_apply will not return immediately, but after the completion of the task in the block will not return, is the function of synchronous execution.
  • How to use:
      1. dispatch_queue_t globalqueue = dispatch_get_global_queue (0, 0);
      2. NSLog (@ "current task");
      3. Dispatch_async (Globalqueue, ^{
      4. dispatch_queue_t applyqueue = dispatch_get_global_queue (0, 0);
      5. The first parameter, the number of times the 3--block executes
      6. The second parameter, the queue to which the Applyqueue--block task is submitted
      7. The third parameter, block--tasks that need to be performed repeatedly
      8. Dispatch_apply (3, Applyqueue, ^ (size_t index) {
      9. NSLog (@ "Current index%@", @ (index));
      10. Sleep (1);
      11. });
      12. NSLog (@ "dispatch_apply execution complete");
      13. dispatch_queue_t mainqueue = Dispatch_get_main_queue ();
      14. Dispatch_async (Mainqueue, ^{
      15. NSLog (@ "Back to the main thread update UI");});
      16. });
      17. NSLog (@ "next task");
  • Note: calling dispatch_apply directly on the main thread will block the main thread, in order to not block the main thread, generally put dispatch_apply in the asynchronous queue, and then notify the main thread after the completion of execution
      1. Dispatch_suspend/dispatch_resume
    • Features: provides the ability to suspend and resume queues, simply to pause and resume tasks on the queue. But the "hang" here does not guarantee that the block that is running on the queue can be stopped immediately

How to use:

      1. dispatch_queue_t queue = dispatch_queue_create ("ME.TUTUGE.TEST.GCD",  dispatch_queue_ SERIAL);
      2. //Submit first block, Delay 5 second print
      3. Dispatch_async (queue, ^{
      4.     [nsthread sleepfortimeinterval:5];
      5.     nslog (@ "Block2 printf after 5 seconds ...");
      6. //Submit second block, delay 15 seconds to print
      7. Dispatch_async (queue, ^{
      8.     [nsthread sleepfortimeinterval:15];
      9.     nslog (@ "Block1 printf after 15 seconds  ...");
      10. });
      11. //Delay one second
      12. NSLog (@ "Sleep 1 second ...");
      13. [nsthread sleepfortimeinterval:1];
    1. Suspend queue
    2. Dispatch_suspend (queue);
    3. 10 seconds delay
    4. NSLog (@ "sleep second ...");
    5. [Nsthread Sleepfortimeinterval:10];
    6. Recovery queue
    7. NSLog (@ "Resume ...");
    8. Dispatch_resume (queue);

Operational ideas:

1.block starts running (five seconds delay printing) While printing sleep 1 second ...,

2. The delay of one second command delayed one second, run to the suspend command, the queue will be paused, but the running Block1 continues to run, five seconds after the run time printing Block1 printf after 5 seconds ...

3. After running the Block1, the queue is really paused. Then run print sleep second ... After the delay of 10 seconds command, the delay of 10 seconds, 10 seconds after the run print; resume ...; To the Recovery queue command, the queue resumes running (Block2 starts running), after 15 seconds Block2 run, print Block2 printf after the seconds ...

So after Dispatch_suspend hangs up the queue, the first block is still running, and the output is normal.

Operation Result:

      1. 00:32:09.903 Sleep 1 Second ...
      2. 00:32:10.910 suspend ...
      3. 00:32:10.910 Sleep Ten Second ...
      4. 00:32:14.908 Block1 printf after 5 seconds ... (Block1 continuous operation)
      5. 00:32:20.911 Resume ...
      6. 00:32:35.912 Block2 printf after the seconds ...

Note:Dispatch_suspend does not immediately halt the running block, but suspends subsequent block execution after the current block execution is complete. So if you want to pause a block that is running on the queue, do not use dispatch_suspend

      1. Dispatch_once
    • function: It is widely used in the code of Singleton, cache, etc. to ensure that a task is executed at initialization time. Meaningless in a single-threaded program, but in a multithreaded program, its low load, high dependency, simple interface and other characteristics
    • How to use:
    1. Static dispatch_once_t once;
    2. Dispatch_once (&once, ^{
    3. Single example code
    4. });
    • Note the point: dispatch_once_t must be global or Static Change Volume

Sample code that lets the program run long in the background:

@property (Assign, nonatomic) Uibackgroundtaskidentifier backgroundupdatetask;

APPDELEGATE.M file

-(void) Applicationdidenterbackground: (uiapplication *) application

{

[Self beingbackgroundupdatetask];

Add the code that you need to run long

[Self endbackgroundupdatetask];

}

-(void) Beingbackgroundupdatetask

{

Self.backgroundupdatetask = [[UIApplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{

[Self endbackgroundupdatetask];

}];

}

-(void) Endbackgroundupdatetask

{

[[UIApplication sharedapplication] endBackgroundTask:self.backgroundUpdateTask];

Self.backgroundupdatetask = Uibackgroundtaskinvalid;

}

iOS Learning 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.