[IOS Multithreading & Networking-1.2]-multithreaded GCD

Source: Internet
Author: User
Tags gcd

A.GCD Basic Use Concept of 1.GCDWhat is GCD
The full name is Grand Central Dispatch, which translates as "the backbone scheduler"
Pure C language, provides a lot of powerful functions

Advantages of GCD
GCD is Apple's solution for multi-core parallel computing
GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core)
GCD automatically manages the life cycle of threads (create threads, schedule tasks, destroy threads)
Programmers just need to tell gcd what tasks they want to perform, without having to write any thread management code 2. Tasks and QueuesThere are 2 core concepts in GCD
Task: what action to take
Queues: Used to store tasks

The use of GCD is a 2-step process
customizing tasks
Identify the things you want to do

Add a task to a queue
GCD will automatically take the tasks in the queue and put them in the corresponding thread.
The removal of a task follows the FIFO principle of the queue: first-in, LIFO, and post- 3. Perform TasksThere are 2 functions for performing tasks in GCD
Perform tasks in a synchronized manner
Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block);
Queue: Queues
Block: Task

Perform a task in an asynchronous manner
Dispatch_async (dispatch_queue_t queue, dispatch_block_t block);

The difference between synchronous and asynchronous
Synchronization: Executing in the current thread
Async: Executing in another thread 4. Types of QueuesThe GCD queue can be divided into 2 major types
Concurrent queues (Concurrent Dispatch queue)
Multiple tasks can be executed concurrently (concurrently) (automatic opening of multiple threads concurrently executing tasks)
concurrency function is only valid under asynchronous (Dispatch_async) functions

Serial Queue (Serial Dispatch queue)
Let the task execute one after the other (once a task has finished executing, then the next task is performed) 5. Synchronous & Asynchronous Serial & ConcurrencyThere are 4 terms that are more easily confused: synchronous, asynchronous, concurrent, serial
Synchronous and asynchronous determine whether to open a new thread
Synchronous: Performs a task in the current thread without the ability to open a new thread
Async: Perform a task in a new thread with the ability to open a new thread

Concurrency and serialization determine how tasks are executed
Concurrency: Multiple tasks concurrently (concurrently) executed
Serial: Once a task is completed, the next task is performed 6. Concurrent QueuesThe GCD default already provides a global concurrency queue for the entire app to use, without the need to manually create
Using the Dispatch_get_global_queue function to obtain a global concurrency queue
dispatch_queue_t Dispatch_get_global_queue (
dispatch_queue_priority_t priority,//queue priorities
unsigned long flags); This parameter is temporarily useless and can be used with 0
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0); Get global concurrency Queue

Priority of global concurrent queues
#define DISPATCH_QUEUE_PRIORITY_HIGH 2//High
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0//default (Medium)
#define Dispatch_queue_priority_low (-2)//Low
#define Dispatch_queue_priority_background int16_min//Backstage 7. Serial QueueThere are 2 ways to get serial in GCD
To create a serial queue using the Dispatch_queue_create function
dispatch_queue_t
Dispatch_queue_create (const char *label,//queue name
dispatch_queue_attr_t attr); Queue properties, typically null
dispatch_queue_t queue = dispatch_queue_create ("Cn.itcast.queue", NULL); Create
Dispatch_release (queue); Non-Arc needs to release manually created queues

Use the primary queue (the queue associated with the mainline threads)
The primary queue is a special serial queue that comes with GCD
Tasks placed in the master queue are placed in the main thread to execute
Use Dispatch_get_main_queue () to get the home row
dispatch_queue_t queue = Dispatch_get_main_queue ();

8. Various combinations 9. Inter-thread communicationReturning from a child thread to the main thread
Dispatch_async (
Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform time-consuming asynchronous operations ...
Dispatch_async (Dispatch_get_main_queue (), ^{
Go back to the main thread and perform a UI refresh operation
});
}); 10. Delay ExecutionThere are 2 ways that iOS typically delays execution
Methods for calling NSObject
[Self performselector: @selector (Run) Withobject:nil afterdelay:2.0];
Call the self's Run method after 2 seconds

Using the GCD function
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{
Execute the code here asynchronously after 2 seconds ...

}); 11. Disposable CodeUse the Dispatch_once function to ensure that a piece of code is executed only 1 times during program operation
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
Execute code only 1 times (this is thread-safe by default)
}); 12. Queue Groups GroupThere are 1 different needs
First: Perform 2 time-consuming operations asynchronously, respectively
Second: Wait for 2 asynchronous operations to complete, then return to the main thread to perform the operation

If you want to implement these requirements quickly and efficiently, consider using queue groups
dispatch_group_t group = Dispatch_group_create ();
Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform 1 time-consuming asynchronous operations
});
Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform 1 time-consuming asynchronous operations
});
Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{
When the previous asynchronous operation is complete, return to the main thread ...
}); B. Single-Case mode 1. Singleton mode conceptThe role of the singleton pattern
You can guarantee that there is only one instance of a class when the program is running, and that the instance is easy for outside access
Thus conveniently control the number of instances, and save system resources

The use of single-case mode
Share a single resource throughout the application (this resource only needs to be initialized 1 times)

The singleton pattern is different in the ARC\MRC environment, it needs to write 2 different sets of code
You can use a macro to determine whether an arc environment
#if __has_feature (OBJC_ARC)
ARC
#else
Mrc
#endif 2. Single case mode-arcIn Arc, the implementation of the singleton mode
Keep an instance of global static in. m
Static ID _instance;

Override Allocwithzone: Method, create a unique instance here (Note thread safety)
+ (ID) allocwithzone: (struct _nszone *) zone
{
@synchronized (self) {
if (!_instance) {
_instance = [Super Allocwithzone:zone];
}
}
return _instance;
Provides 1 class methods for accessing unique instances from outside
+ (Instancetype) Sharedsoundtool
{
@synchronized (self) {
if (!_instance) {
_instance = [[Self alloc] init];
}
}
return _instance;
} 3. Singleton mode-Non-ArcNon-arc (MRC), single-instance mode implementation (several steps more than ARC)
Implementing Copywithzone: Methods
+ (ID) copywithzone: (struct _nszone *) zone
{
return _instance;
}

Implementing a memory management approach
-(ID) retain {return self;}
-(Nsuinteger) Retaincount {return 1;}
-(OneWay void) Release {}
-(ID) autorelease {return self;}

[IOS Multithreading & Networking-1.2]-multithreaded 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.