Multithreading introduction and the use of GCD

Source: Internet
Author: User
Tags gcd

Multithreading Introduction:

For any iOS app, when the program is running, a main thread (Mainthread) is created by default, and the main thread is designed to handle the operations of Uikit objects, such as display and update of interfaces, actions triggered by user events, and so on. (Remember this, all UI-related operations are done in the main thread)

For an app, there is a need to introduce multiple threads, largely because some operations are time-consuming, such as sending a network request and waiting for the server to respond, a time-consuming operation that cannot be manipulated in the main thread, because the main thread is used in the waiting time, The user is not able to do any interactive actions, which can greatly affect the user experience. For time-consuming operations, it is necessary to create another thread, put it into the background processing, and then return to the main thread to set the UI interface when the processing is finished, which involves knowledge of inter-thread communication.

So what is GCD?

GCD (Grand Central Dispatch) technology, Apple was first used in OSX, followed by the introduction of GCD technology in iOS. In particular, the use of GCD has become more widespread and important after the iphone has upgraded the CPU to multicore. Compared to Nsthread, GCD has completely shielded the concept of the thread, but introduced the task and queue, put the task in the queue to execute, set the type of task and queue, the thread management of the transaction is completely referred to the GCD to deal with, greatly simplifying the difficulty of multi-task development. In GCD, programmers no longer need to care about threading operations (such as thread creation, thread destruction, thread scheduling), but instead introduce two core concepts of tasks and queues.

Because GCD encapsulates thread management, when engineers use GCD, they simply add the task (usually encapsulated in a block) to a queue and work on the thread scheduler, which is fully gcd done.

When you use GCD to handle multitasking, just follow the steps below to perform the task.

    • Define the task content to be performed in the Block;
    • Add a task to a queue

GCD to tasks in the queue, according to the "FIFO" principle, according to the order in which tasks are added to the queue to process the queue, GCD automatically distributes work across multiple threads based on the type of task and queue.

In GCD, a queue is an important concept. The system provides several predefined queues, including the primary queue where the application can be obtained (the task is always executed on the main thread , and the UI operation needs to be done in the main queue ).

GCD queues are added to the GCD queue in strict accordance with the "FIFO" principle, and are always executed in the order in which they are queued.

The most common in GCD are serial queues and parallel queues:

    1. Parallel queues: Tasks in a parallel queue can be assigned to execute across multiple threads, and the principle of allocation is controlled by GCD, so that tasks in parallel queues, although allocations are performed in FIFO, are likely to have different completion times because each task is assigned to a different thread. That is, post-assigned tasks may be completed first , and concurrent queues must be used in conjunction with asynchronous tasks (using Dispatch_async ()) to make sense.
    2. Serial queue: The tasks in the serial queue are completed one at a time, and when a task is completed, the next task is performed, so the serial queue corresponds to one thread execution.
    3. Primary queue: The primary queue is also a serial queue, and the tasks in the primary queue are executed in the main thread.

The next step is to use the code to clearly demonstrate the functionality of GCD.

1     //CGD in the form of a queue, features: "FIFO"2 #pragmaMark-use GCD to create a serial queue3     //First: System-provided methods for creating a serial queue (main thread main)4dispatch_queue_t queue =dispatch_get_main_queue ();5     //in real development if you need to create a serial queue, it is more customary to use this6     //The second type: Go to create yourself (serial queue: SERIAL)7     //parameter one: is a macro provided by the system8     //parameter two: is the reserved field of the system9     //The position of the two parameters is not strictly limited, just write this two parameters canTendispatch_queue_t queue = Dispatch_queue_create (dispatch_queue_serial,0); One      A #pragmaMark-Create a parallel queue using GCD - //first method (global parallel queue) -     //parameter One: priority (there are four, no obvious difference) the     //parameter two: System reserved fields -dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0); -     //The second way: Create your own -     //parameter one: Represents a name for your queue +     //parameter two: System-provided macros -dispatch_queue_t queue = Dispatch_queue_create ("Myqueue", dispatch_queue_concurrent); +     //there is a queue to create sub-threads according to the queue, there is no fixed order, random execution, following the creation of 5 sub-threads added to the parallel queue, the operation can be seen, the execution is not a fixed order. ADispatch_async (Queue, ^{ atNSLog (@"111%@, 111%@", [Nsthread CurrentThread], [Nsthread mainthread]); -     }); -      -Dispatch_async (Queue, ^{ -NSLog (@"222%@, 222%@", [Nsthread CurrentThread], [Nsthread mainthread]); -     }); in      -Dispatch_async (Queue, ^{ toNSLog (@"333%@, 333%@", [Nsthread CurrentThread], [Nsthread mainthread]); +     }); -      theDispatch_async (Queue, ^{ *NSLog (@"444%@, 444%@", [Nsthread CurrentThread], [Nsthread mainthread]); $     });Panax Notoginseng      -Dispatch_async (Queue, ^{ theNSLog (@"555%@, 555%@", [Nsthread CurrentThread], [Nsthread mainthread]); +     }); A      the #pragmaMark--a few seconds to do everything. +     //Delay Queue -Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3.0*NSEC_PER_SEC)), Dispatch_get_main_queue (), ^{ $NSLog (@"after 3 seconds"); $     }); -  - #pragmaMark-Repeatedly add multiple tasks to a queue the     //or create a parallel queue (CONCURRENT: Parallel, corresponds to the serial that is described above) -dispatch_queue_t queue = Dispatch_queue_create (0, dispatch_queue_concurrent);Wuyi     //Add multiple Tasks the     //parameter One: number of tasks (repeat 100 times) -     //parameter two: queue name, you can get a name, here I named index WuDispatch_apply ( -, queue, ^(size_t index) { -NSLog (@"%ld", index); About     }); $      - #pragmaMark-Group Group -     //Create a grouping (in order to be a listener function) -dispatch_group_t Group =dispatch_group_create (); A     //Create a parallel queue +dispatch_queue_t queue = Dispatch_queue_create (0, dispatch_queue_concurrent); the     //Create task One -Dispatch_group_async (group, queue, ^{ $NSLog (@"I'm the Mission one ."); the     }); theDispatch_group_async (group, queue, ^{ theNSLog (@"I'm mission two ."); the     }); -      in     //task-supervised functions that monitor the execution of all tasks must be placed at the bottom of all Tasks theDispatch_group_notify (group, queue, ^{ theNSLog (@"I'm the Proctor ."); About});
gcd serial, parallel

Multithreading introduction and the use of 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.