Multithreading and network development for iOS: multithreading GCD and ios multithreading development gcd

Source: Internet
Author: User

Multithreading and network development for iOS: multithreading GCD and ios multithreading development gcd

Master haomeng is devoted to his contribution and respects the author's Labor achievements. Do not repost them.

If the article is helpful to you, you are welcome to donate to the author, support haomeng master, the amount of donation is free, focusing on your mind ^_^

I want to donate: Click to donate

Cocos2d-X source code download: point I send

Game official download: http://dwz.cn/RwTjl

Game video preview: http://dwz.cn/RzHHd

Game Development blog: http://dwz.cn/RzJzI

Game source code transfer: Http://dwz.cn/Nret1


A. GCD basically uses 1. What is GCD?
The full name is Grand Central Dispatch"
Pure C language, providing a lot of powerful functions

GCD advantages
GCD is a solution developed by Apple for multi-core parallel computing
GCD will automatically use more CPU cores (such as dual-core and quad-core)
GCD automatically manages the thread lifecycle (creating threads, scheduling tasks, and destroying threads)
The programmer only needs to tell GCD what task to execute, and does not need to write any thread Management Code. 2. There are two core concepts in task and queue GCD.
Task: What operations are performed
Queue: used to store tasks

There are two steps to use GCD.
Custom task
Determine what you want to do

Add a task to the queue
GCD automatically extracts tasks from the queue and puts them in the corresponding thread for execution.
The removal of a task follows the FIFO principle of the queue: first-in-first-out, and then-out. 3. There are two functions in the GCD for executing the task.
Execute tasks in synchronous Mode
Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block );
Queue: queue
Block: Task

Execute tasks in asynchronous mode
Dispatch_async (dispatch_queue_t queue, dispatch_block_t block );

Differences between synchronous and asynchronous
Synchronization: executed in the current thread
Asynchronous: Execute in another thread 4. Queue type GCD queues can be divided into two main types
Concurrent Dispatch Queue)
Allows concurrent (concurrent) Execution of multiple tasks (automatically enabling multiple threads to execute tasks simultaneously)
The concurrency function is valid only when the asynchronous (dispatch_async) function is used.

Serial Queue (Serial Dispatch Queue)
Let the task be executed one by one (after a task is executed, execute the next task. four Terms of synchronous & asynchronous serial & concurrency are confusing: synchronous, asynchronous, concurrent, and serial
Synchronization and Asynchronization determine whether to enable new threads
Synchronization: The task is executed in the current thread and cannot start a new thread.
Asynchronous: execute tasks in new threads and enable new threads.

Concurrency and serial determine the task execution mode.
Concurrency: Concurrent (concurrent) Execution of multiple tasks
Serial: After a task is executed, execute the next task. 6. By default, the concurrent queue GCD provides a global concurrent queue for the entire application.
Use the dispatch_get_global_queue function to obtain the global concurrent queue.
Dispatch_queue_t dispatch_get_global_queue (
Dispatch_queue_priority_t priority, // queue priority
Unsigned long flags); // this parameter is temporarily useless. Use 0.
Dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // obtain the 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 // backend 7. There are two methods to obtain serial data in the serial queue GCD.
Use the dispatch_queue_create function to create a serial queue
Dispatch_queue_t
Dispatch_queue_create (const char * label, // queue name
Dispatch_queue_attr_t attr); // queue attribute, which can be NULL.
Dispatch_queue_t queue = dispatch_queue_create ("cn. itcast. queue", NULL); // create
Dispatch_release (queue); // non-ARC queue needs to be released manually

Use the main queue column (queue associated with the main thread)
The main queue is a special serial queue that comes with GCD.
All tasks in the main queue are executed in the main thread.
Use dispatch_get_main_queue () to obtain the main queue Column
Dispatch_queue_t queue = dispatch_get_main_queue ();

8. Various Combinations 9. Inter-thread communication from sub-thread back to main thread
Dispatch_async (
Dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Execute time-consuming asynchronous operations...
Dispatch_async (dispatch_get_main_queue (), ^ {
// Return to the main thread and perform the UI refresh operation
});
}); 10. There are two common iOS delayed execution methods.
Call NSObject Method
[Self defined mselector: @ selector (run) withObject: nil afterDelay: 2.0];
// Call self's run method 2 seconds later

Use 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. Using the dispatch_once function for one-time Code ensures that a piece of code is executed only once during the program running
Static dispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
// Only run the code once (thread-safe by default)
}); 12. The queue group has such a requirement.
First, perform two time-consuming operations asynchronously.
Second, after two asynchronous operations are completed, return to the main thread to execute the operation.

If you want to quickly and efficiently implement the above requirements, you can use the queue Group
Dispatch_group_t group = dispatch_group_create ();
Dispatch_group_async (group, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Execute one time-consuming Asynchronous Operation
});
Dispatch_group_async (group, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Execute one time-consuming Asynchronous Operation
});
Dispatch_group_policy (group, dispatch_get_main_queue (), ^ {
// After all the preceding asynchronous operations are completed, return to the main thread...
}); B. Singleton Mode 1. Singleton mode concept the role of Singleton Mode
It can ensure that there is only one instance for a class during the program running, and the instance is easy for external access.
This allows you to easily control the number of instances and save system resources.

Use Cases of Singleton Mode
Share a resource in the entire application (this resource only needs to be created and initialized once)

The Singleton mode varies in the ARC \ MRC environment and requires two sets of different codes.
Macro can be used to determine whether it is an ARC environment
# If _ has_feature (objc_arc)
// ARC
# Else
// MRC
# Endif 2. Singleton mode-Implementation of Singleton mode in ARCARC
Keep a Global static instance in. m.
Static id _ instance;

Override allocWithZone: method to create a unique instance (pay attention to thread security)
+ (Id) allocWithZone :( struct _ NSZone *) zone
{
@ Synchronized (self ){
If (! _ Instance ){
_ Instance = [super allocWithZone: zone];
}
}
Return _ instance;
} One class method is provided to allow external access to a unique instance.
+ (Instancetype) sharedSoundTool
{
@ Synchronized (self ){
If (! _ Instance ){
_ Instance = [[self alloc] init];
}
}
Return _ instance;
} 3. Singleton mode-non-ARC (MRC); Implementation of Singleton mode (several more steps than ARC)
Implementation of copyWithZone: Method
+ (Id) copyWithZone :( struct _ NSZone *) zone
{
Return _ instance;
}

Memory Management
-(Id) retain {return self ;}
-(NSUInteger) retainCount {return 1 ;}
-(Oneway void) release {}
-(Id) autorelease {return self ;}

Master haomeng is devoted to his contribution and respects the author's Labor achievements. Do not repost them.

If the article is helpful to you, you are welcome to donate to the author, support haomeng master, the amount of donation is free, focusing on your mind ^_^

I want to donate: Click to donate

Cocos2d-X source code download: point I send

Game official download: http://dwz.cn/RwTjl

Game video preview: http://dwz.cn/RzHHd

Game Development blog: http://dwz.cn/RzJzI

Game source code transfer: Http://dwz.cn/Nret1

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.