Object-c about the use of GCD multi-threading

Source: Internet
Author: User
Tags gcd

"' OBJC
1 main differences between concurrent queues and global concurrent queues created with the Crearte function:
1) Global concurrent queues are inherently default throughout the application and have a total of four concurrent queues for high priority, default priority, low priority, and background priority, and we just choose one of them for direct use. The CREATE function is a real deal that creates a queue from the beginning.
2) before iOS6.0, all functions with the Create and retain in GCD are required to do a release operation at the end. The home row and global concurrent queues do not require us to release manually. Of course, after iOS6.0 GCD has been incorporated into the ARC memory management category, even objects created with the retain or create function are no longer required to be manually released by the developer, and we treat the GCD as if the normal OC object is OK.
3) When using the fence function, Apple officially specifies that the fence function is only valid when used with a concurrent queue created by the CREATE function itself (no specific reason given)
4) Other differences are related to XNU kernel system-level threading programming, not listed.
5) give some references (you can study it yourself):
gcdapi:https://developer.apple.com/library/ios/documentation/performance/reference/gcd_libdispatch_ref/ Index.html#//apple_ref/c/func/dispatch_queue_create
Libdispatch version Source: http://www.opensource.apple.com/source/libdispatch/libdispatch-187.5/
GCD Open Source: http://libdispatch.macosforge.org
```
=================================================================================

# # # #2 Single-case mode
"' OBJC
1 Basic Concepts
1) Single case mode
There is only one instance of a class during program run
2) Use the occasion
Share a single resource throughout the application (this resource only needs to be initialized 1 times)

2 ARC Implementation single case
1) steps
01 provides a static modified global variable inside the class
02 provides a class method for easy access to the outside world
03 overriding the +allocwithzone method to ensure that only one memory space is allocated once for a single object
04 for Rigor, rewrite the-copywithzone method and the-mutablecopywithzone method

2) Related code
Provides a static modified global variable that strongly references an instance of a singleton object that has already been instantiated
Static Xmgtools *_instance;

Class method, returning a singleton object
+ (Instancetype) sharetools
{
Note: It is recommended to use self instead of using the class name tools directly (consider inheritance)

return [[Self alloc]init];
}

Guaranteed to allocate only one storage space at a time
+ (Instancetype) Allocwithzone: (struct _nszone *) zone
{
Using one-time code in GCD
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instance = [Super Allocwithzone:zone];
// });

Use lock to ensure that only one storage space is allocated
@synchronized (self) {
if (_instance = = nil) {
_instance = [Super Allocwithzone:zone];
}
}
return _instance;
}
/*
1. Mutablecopy creates a new mutable object and initializes it to the value of the original object, and the reference count for the new object is 1;
2. Copy returns an immutable object. In two cases: (1) The Wakahara object is an immutable object, then the original object is returned, and its reference count is added 1, and (2) The Wakahara object is a mutable object, then a new immutable object is created and initialized to the value of the original object, and the reference count of the new object is 1.
*/
Make the code more rigorous
-(nonnull ID) Copywithzone: (Nullable Nszone *) zone
{
return [[Self class] allocwithzone:zone];
return _instance;
}

-(nonnull ID) Mutablecopywithzone: (Nullable Nszone *) zone
{
return _instance;
}

3 MRC Implementation single case
1) Implementation steps
01 provides a static modified global variable inside the class
02 provides a class method for easy access to the outside world
03 overriding the +allocwithzone method to ensure that only one memory space is allocated once for a single object
04 for Rigor, rewrite the-copywithzone method and the-mutablecopywithzone method
05 overriding the Release method
06 overriding the Retain method
07 We recommend that you return a maximum value in the Retaincount method
2) Configuring MRC Environment Knowledge
01 Note that arc is not a garbage collection mechanism, it is a compiler feature
02 Configuring the MRC Environment: Build setting Search automatic ref-> Modify to No
3) Related code
Provides a static modified global variable that strongly references an instance of a singleton object that has already been instantiated
Static Xmgtools *_instance;

Class method, returning a singleton object
+ (Instancetype) sharetools
{
Note: It is recommended to use self instead of using the class name tools directly (consider inheritance)

return [[Self alloc]init];
}

Guaranteed to allocate only one storage space at a time
+ (Instancetype) Allocwithzone: (struct _nszone *) zone
{
Using one-time code in GCD
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instance = [Super Allocwithzone:zone];
// });

Use lock to ensure that only one storage space is allocated
@synchronized (self) {
if (_instance = = nil) {
_instance = [Super Allocwithzone:zone];
}
}
return _instance;
}

Make the code more rigorous
-(nonnull ID) Copywithzone: (Nullable Nszone *) zone
{
return [[Self class] allocwithzone:zone];
return _instance;
}

-(nonnull ID) Mutablecopywithzone: (Nullable Nszone *) zone
{
return _instance;
}

In the MRC environment, if the user retain once, then directly return the instance variable, not the reference counter +1
If the user is released one time, then nothing is done, because the singleton mode in the entire program running process has only one copy, the program exits after the release, so do not need to operate on the reference counter
-(OneWay void) release
{
}

-(Instancetype) retain
{
return _instance;
}

Idiomatic, experienced programmers print Retaincount This value can be guessed that this is a singleton
-(Nsuinteger) Retaincount
{
return maxfloat;
}

4 generic version
1) An interesting conversation
01 Q: Is writing a single sample code applicable in both ARC and MRC environments?
Answer: You can use conditional compilation to determine whether the current project environment is arc or MRC
02 Q: What is the code for conditional compilation?
Answer: Conditional compilation
#if __has_feature (OBJC_ARC)
If it's arc, then execute the code here 1.
#else
If it is not arc, then execute the Agent code 2
#endif
03 Q: In the project often need to implement a lot of singleton, such as download, network requests, music playback and so on, weak weak Ask a single case can be inherited?
A: Single example is not allowed to inherit, if you want to write at once, around the use, then recommend the Pro use with parameters of the macro definition!
04 Q: How does the macro definition get done?
A: Well, look back at my code, pro.

2) Use a macro with parameters to complete the common version of the single mode code
01 Note Conditional compilation code cannot be included in the macro definition
02 macro-defined code only needs to be written once, and then dragged directly into the project with OK
=================================================================================
```

# # # #3 Nsoperation
(1) Nsoperation Basic use
"' OBJC
1) Related concepts
Nsoperation is the packaging of GCD.
22 Core Concepts "Queue + operation"

2) Basic use
The nsoperation itself is an abstract class, only its subclasses
23 subcategories are: Nsblockoperation, nsinvocationoperation, and custom inherited classes from Nsoperation
Nsoperation and Nsoperationqueue in combination for multithreading concurrency

3) Related code
Nsinvocationoperation
1. Encapsulation operation
/*
First parameter: target object
Second parameter: The method to be called by the operation, with a maximum of one parameter
The third argument: call the parameter passed by the method, and if the method does not accept the argument, the value is nil
*/
Nsinvocationoperation *operation = [[Nsinvocationoperation alloc]
Initwithtarget:self selector: @selector (run) Object:nil];

2. Start the operation
[Operation start];
---------------
Nsblockoperation
1. Encapsulation operation
/*
Nsblockoperation provides a class method for encapsulating operations in this class of methods
*/
Nsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^{
Executing in the main thread
NSLog (@ "---download1--%@", [Nsthread CurrentThread]);
}];

2. Append operation, append operation executed in child thread
[Operation Addexecutionblock:^{
NSLog (@ "---download2--%@", [Nsthread CurrentThread]);
}];

[Operation Addexecutionblock:^{
NSLog (@ "---download3--%@", [Nsthread CurrentThread]);
}];

3. Start the execution action
[Operation start];

---------------
03 Custom Nsoperation
How do I encapsulate an operation?
Custom Nsoperation, by overriding the internal main method to implement encapsulation operations
-(void) Main
{
NSLog (@ "--main--%@", [Nsthread CurrentThread]);
}

How do I use it?
1. Instantiate a custom Action object
Xmgoperation *op = [[Xmgoperation alloc]init];

2. Perform the action
[op start];
```
(2) Nsoperationqueue basic use
"' OBJC
1) Two types of queues in nsoperation
01 The primary queue is obtained through Mainqueue, and all tasks placed in the main queue are executed on the primary thread.
02 Non-Home Row Direct Alloc init out of queue. The non-Home column also has concurrent and serial capabilities to control whether the task is executed concurrently or serially by setting the maximum Concurrency Number property

2) Related code
Custom Nsoperation
-(void) customoperation
{
1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Encapsulation operation
Benefits: 1. Information hiding
2. Code Reuse

Xmgoperation *OP1 = [[Xmgoperation alloc]init];
Xmgoperation *OP2 = [[Xmgoperation alloc]init];

3. Adding actions to the queue
[Queue ADDOPERATION:OP1];
[Queue ADDOPERATION:OP2];
}

Nsblockoperation
-(void) block
{
1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Encapsulation operation
Nsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "1----%@", [Nsthread CurrentThread]);
}];

Nsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "2----%@", [Nsthread CurrentThread]);

}];

[Op2 addexecutionblock:^{
NSLog (@ "3----%@", [Nsthread CurrentThread]);
}];

[Op2 addexecutionblock:^{
NSLog (@ "4----%@", [Nsthread CurrentThread]);
}];

3. Adding actions to the queue
[Queue ADDOPERATION:OP1];
[Queue ADDOPERATION:OP2];

Add: A simple method
[Queue addoperationwithblock:^{
NSLog (@ "5----%@", [Nsthread CurrentThread]);
}];

}

Nsinvocationoperation
-(void) invocation
{
/*
Queues in the GCD:
Serial queue: Self-created, home row
Concurrent queues: Created by yourself, global concurrent queues

Nsoperationqueue
Main queue: [Nsoperationqueue mainqueue]; everything placed in the master queue is executed in the main thread
Non-Home column: [[[Nsoperationqueue Alloc]init], concurrent and serial, default is concurrent execution
*/

1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Encapsulation operation
Nsinvocationoperation *OP1 = [[nsinvocationoperation alloc]initwithtarget:self selector: @selector (download1) object: NIL];

Nsinvocationoperation *OP2 = [[nsinvocationoperation alloc]initwithtarget:self selector: @selector (download2) object: NIL];


Nsinvocationoperation *OP3 = [[nsinvocationoperation alloc]initwithtarget:self selector: @selector (download3) object: NIL];


3. Add encapsulated operations to the queue
[Queue Addoperation:op1];//[op1 start]
[Queue ADDOPERATION:OP2];
[Queue ADDOPERATION:OP3];
}
```
(3) Nsoperation other uses
"' OBJC
1) Set maximum concurrent number "control task concurrency and serial"
1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Set the maximum number of concurrent
Note: This property needs to be set before the task is added to the queue.
This property controls whether the queue is executed serially or concurrently
If the maximum concurrent number equals 1, then the queue is serial, if it is greater than 1 then it is parallel
The maximum number of concurrency for the system has a default value of-1, and if the property is set to 0, no tasks are performed
Queue.maxconcurrentoperationcount = 2;

2) Pause and resume and cancel
Set pause and resume
Suspended set to Yes to pause, suspended set to No for recovery
Pause indicates that the next task in the queue is not resumed and the suspend operation can be resumed
if (self.queue.isSuspended) {
self.queue.suspended = NO;
}else
{
self.queue.suspended = YES;
}

Cancel all operations inside the queue
After cancellation, the next operation of the currently executing operation will no longer execute, and will never be executed, as if all subsequent tasks were removed from the queue
The cancel operation is not recoverable
[Self.queue cancelalloperations];

---------Custom Nsoperation Cancel the operation--------------------------
-(void) Main
{
Time-consuming Operation 1
for (int i = 0; i<1000; i++) {
NSLog (@ "Task 1-%d--%@", I,[nsthread CurrentThread]);
}
NSLog (@ "+++++++++++++++++++++++++++++++++");

Apple's official recommendation is that each time a time-consuming operation is performed, the current queue is canceled, and if so, exit directly
The advantage is that it can improve the performance of the program
if (self.iscancelled) {
Return
}

Time-consuming Operation 2
for (int i = 0; i<1000; i++) {
NSLog (@ "Task 1-%d--%@", I,[nsthread CurrentThread]);
}

NSLog (@ "+++++++++++++++++++++++++++++++++");
}
```
(4) Nsoperation for inter-thread communication
"' OBJC
1) Open sub-thread download picture
1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Encapsulate the operation and add it to the queue in a convenient way
[Queue addoperationwithblock:^{

3. Download the image in the block
Nsurl *url = [Nsurl urlwithstring:@ "http://news.51sheyuan.com/uploads/allimg/111001/133442IB-2.jpg"];
NSData *data = [NSData Datawithcontentsofurl:url];
UIImage *image = [UIImage imagewithdata:data];
NSLog (@ "Download picture operation--%@", [Nsthread CurrentThread]);

4. Go back to the main thread to refresh the UI
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{
Self.imageView.image = image;
NSLog (@ "Refresh UI Action---%@", [Nsthread CurrentThread]);
}];
}];

2) Download multiple picture synthesis case (set operation dependency)
02 Comprehensive case
-(void) download2
{
NSLog (@ "----");
1. Create a queue
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];

2. Package operation Download Picture 1
Nsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{

Nsurl *url = [Nsurl urlwithstring:@ "http://h.hiphotos.baidu.com/zhidao/pic/item/ 6a63f6246b600c3320b14bb3184c510fd8f9a185.jpg "];
NSData *data = [NSData Datawithcontentsofurl:url];

Get the picture data
Self.image1 = [UIImage imagewithdata:data];
}];


3. Package Operation Download Picture 2
Nsblockoperation *OP2 = [Nsblockoperation blockoperationwithblock:^{
Nsurl *url = [Nsurl urlwithstring:@ "http://pic.58pic.com/58pic/13/87/82/27Q58PICYje_1024.jpg"];
NSData *data = [NSData Datawithcontentsofurl:url];

Get the picture data
Self.image2 = [UIImage imagewithdata:data];
}];

4. Compositing pictures
Nsblockoperation *combine = [Nsblockoperation blockoperationwithblock:^{

4.1 Opening the graphics context
Uigraphicsbeginimagecontext (Cgsizemake (200, 200));

4.2 Painting Image1
[Self.image1 drawinrect:cgrectmake (0, 0, 200, 100)];

4.3 Painting image2
[Self.image2 drawinrect:cgrectmake (0, 100, 200, 100)];

4.4 Get the picture data according to the graphic context
UIImage *image = Uigraphicsgetimagefromcurrentimagecontext ();
NSLog (@ "%@", image);

4.5 Closing the graphics context
Uigraphicsendimagecontext ();

7. Go back to the main thread to refresh the UI
[[Nsoperationqueue mainqueue]addoperationwithblock:^{
Self.imageView.image = image;
NSLog (@ "Refresh UI---%@", [Nsthread CurrentThread]);
}];

}];

5. Set Operation dependencies
[Combine ADDDEPENDENCY:OP1];
[Combine ADDDEPENDENCY:OP2];

6. Add operations to the queue to execute
[Queue ADDOPERATION:OP1];
[Queue ADDOPERATION:OP2];
[Queue Addoperation:combine];
}
```
(5) Comparison of CD and Nsoperation:
"' OBJC
1) GCD is a pure C language API, while the operations queue is the Object-c object.
2) in GCD, the task is represented by blocks (block), while the block is a lightweight data structure, whereas the action nsoperation in the action queue is a more heavyweight object-c object.
3) whether to use GCD or use nsoperation to see the specific situation

The advantages of nsoperation and nsoperationqueue relative gcd are:
1) Nsoperationqueue can easily call the Cancel method to cancel an operation, and the task in GCD cannot be canceled (after the task is scheduled).
2) Nsoperation can conveniently specify the dependencies between the operations.
3) Nsoperation can provide fine-grained control over Nsoperation objects via KVO (such as listening to whether the current operation has been canceled or completed, etc.)
4) Nsoperation can be conveniently assigned the operation priority. The action priority represents the precedence of this action with other operations in the queue, with high priority operations performed first, followed by low priority.
5) by customizing the subclass of the nsoperation, you can implement operation reuse.
```
=================================================================================

# # # #4 Multi-Image Download Comprehensive sample program
"' OBJC
1 related to knowledge points
01 Dictionary Turn Model
02 Images Repeat Download---memory cache, sandbox cache processing
The UI is not fluent---"Open sub-thread download picture (note the inter-thread communication)
04 Picture Download task is added to queue multiple times---"Action cache processing
05 images do not display problems after download---"Actively refresh the specified line
06 Problems with data confusion in image loading---"Setting up a placeholder image
07 Some fault-tolerant processing in the process of program development
```
=================================================================================

# # # #5 third-party framework
"' OBJC
1 Sdwebimage Basic use (set ImageView picture)
[Cell.imageview sd_setimagewithurl:[nsurl URLWithString:app.icon] placeholderimage:[uiimage imagenamed:@ " Placehoder "];

2 Sdwebimage Internal structure
```

Object-c about the use of GCD multi-threading

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.