MJ-0916-Multithreading 2

Source: Internet
Author: User
Tags gcd

"Delayed execution

Sleepfortimeinterval, not recommended, will block threads

-(void) delay1{

[Nsthread Sleepfortimeinterval:3];

}

Performselector, commonly used, once the task is customized, the thread will continue to execute, and then execute the corresponding code after the time.

-(void) delay2{

[Self performselector: @selector (Download:) withobject:@ "var" afterdelay:3];

}

-(void) Download: (NSString *) var{

NSLog (@ "------download------%@", [Nsthread CurrentThread]);

}

Dispatch_after, recommended, can be executed on child threads (threads are related to queues)

-(void) delay3{

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3 * nsec_per_sec)), Dispatch_get_main_queue (), ^{

NSLog (@ "------download------%@", [Nsthread CurrentThread]);

});

}

"One-time execution

1. Using the tag attribute, after the first execution is marked as Yes, then the tag attribute is judged, and yes does not continue execution.

Tag properties are also reinitialized when new objects are created without using them, invalidating the tags

2. Using Dispatch_once

"Image Watermark (Network)

Scenario One: Multi-threaded asynchronous download

Step1. Download images asynchronously, using Dispatch_async ();

Step2. Merge pictures, images and logos are downloaded and executed again

Scenario Two: Queue groups

Features: Better control of resource downloads, etc. all queue tasks are executed before executing the code in the Dispatch_group_notify method

Step1. Create a queue group dispatch_group_t and add multiple queue tasks

Use __block to allow variable values to be modified in block code blocks

Step2. The Dispatch_group_notify method is executed after the tasks in the queue group are executed

"Single case mode

Key words: 23 kinds of design patterns, predecessors summed up a set of program design, a class only one instance

Step1. Guaranteed to return only one class object. The Alloc method is implemented at the bottom of the Allocwithzone method, so modify the Allocwithzone directly

Step2. Provides a sharexxx method to get singleton objects

Step3. Using the Copy method, the Copy method calls Copywithzone to get an instance of the object, potentially creating a new instance, and in order to prevent a new instance from being generated, implement the Nscopying protocol in the object and implement the Copywithzone method to return a fixed instance.

"is initialized only once with a static modified variable,

Its life cycle is the same as a global variable, but it cannot change scope.

Static global variable can only be accessed within the current file

"refers to an external global variable

The Singleton property recommends using the static modifier to prevent the modified external

Static ID _instance;

Single-instance mode loading method

1. Lazy type (recommended)

2. A hungry man type (load memory to create singleton, less)

"Using GCD to implement a singleton mode

"Non-arc mode (override the release method, do not call the parent class's release to prevent memory from being freed)

Rewrite release, Autorelease, retain, Retaincount four methods to make the counter always 1

"Single-mode code simplification

Extract macro definition (newline plus "\")

With the reference, use the double well number # #分开

"Arc conditional compilation, the macro cannot contain the pound sign #

"4 nsoperation (OC language, based on GCD) commonly used, automatic management

Using queues to implement asynchronous multithreading

Controlling the number of concurrent

Question (Operation dependent)

"Monitoring operation completed

"Queue cancellation, pause, resume

Operations that are not performed after the cancellation queue are cleared

Users can pause the queue when they are consuming memory UI operations, and then continue

Extensions: Custom nsoperation (used to download a large number of network resources at the same time) use the Sdwebimage framework to download pictures

"Advantages

1 Improve development efficiency

2 in order to use a function of the most NB implementation (the industry has specialized)

3

"Shortcomings

1 frequent updates, management difficulties

2 The framework has bugs to wait for the author to resolve

3 A security risk exists after the framework stops updating

4 side reaction developers lack of capacity in this area

MJ Summary

0, the attention point of the thread (master)

1. Do not drive too many threads at the same time (no more than 5 threads, not more than one thread)

2. Threading Concepts

1> main thread: UI thread, displaying, refreshing UI interface, handling events for UI controls

2> Child Threads: Background threads, asynchronous threads

3. Do not place time-consuming operations on the main thread, but on sub-threads

First, Nsthread (master)

1.3 ways to create and start a thread

1> first created, then started

Create

Nsthread *thread = [[Nsthread alloc] initwithtarget:selfselector: @selector (Download:) Object:nil];

Start

[Thread start];

2> Create auto Start

[Nsthread detachnewthreadselector: @selector (Download:) ToTarget:selfwithObject:nil];

3> Implicit creation (auto-start)

[Self performselectorinbackground: @selector (Download:) Withobject:nil];

2. Common methods

1> Get current thread

+ (Nsthread *) CurrentThread;

2> Get the main thread

+ (Nsthread *) Mainthread;

3> sleep (pause) thread

+ (void) Sleepuntildate: (NSDate *) date;

+ (void) Sleepfortimeinterval: (Nstimeinterval) ti;

4> set the name of the thread

-(void) SetName: (NSString *) n;

-(NSString *) name;

Second, thread synchronization (master)

1. Essence: To prevent multiple threads from robbing the same resource for data security issues

2. Implementation: Add a mutex to the code (synchronous lock)

@synchronized (self) {

Locked Code

}

Third, GCD

1. Queues and Tasks

1> tasks: What needs to be done

* Use block to encapsulate tasks

2> Queues: Storing tasks

* Global Concurrent queue: Allows tasks to execute concurrently

dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);

* Create a serial queue yourself: Let the task execute one after the other

dispatch_queue_t queue = dispatch_queue_create ("Cn.heima.queue", NULL);

* Home row: Let the task execute on the main thread

dispatch_queue_t queue = Dispatch_get_main_queue ();

2. Functions that perform tasks

1> synchronous execution: Does not have the ability to open new threads

Dispatch_sync ...

2> Asynchronous execution: Ability to open new threads

Dispatch_async ...

3. Common combinations (master)

1> dispatch_async + global concurrency queue

2> Dispatch_async + self-created serial queue

4. Communication between threads (mastering)

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

});

});

All 5.GCD APIs are automatically imported into this library at Libdispatch.dylib,xcode.

* Main header file: #import <dispatch/dispatch.h>

6. Deferred Execution (master)

1> perform ....

After 3 seconds automatically returns to the current thread called Self's Download: method, and passes the parameter: @ "Http://555.jpg"

[Self performselector: @selector (Download:) withobject:@ "http://555.jpg" afterdelay:3];

2> Dispatch_after ...

Which queue the task is placed in to execute

dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);

Double delay = 3; How many seconds are delayed

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (Delay * nsec_per_sec)), queue, ^{

Tasks that need to be performed after 3 seconds

});

7. Disposable code (Master)

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

The code inside is always executed 1 times during the program's operation.

});

Four, Singleton mode (lazy type)

1.ARC

@interface Hmdatatool:nsobject

+ (instancetype) Shareddatatool;

@end

@implementation Hmdatatool

Used to save unique singleton objects

Static ID _instace;

+ (ID) allocwithzone: (struct _nszone *) zone

{

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

_instace = [Super Allocwithzone:zone];

});

return _instace;

}

+ (Instancetype) Shareddatatool

{

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

_instace = [[Self alloc] init];

});

return _instace;

}

-(ID) Copywithzone: (Nszone *) zone

{

return _instace;

}

@end

2. Non-arc

@interface Hmdatatool:nsobject

+ (instancetype) Shareddatatool;

@end

@implementation Hmdatatool

Used to save unique singleton objects

Static ID _instace;

+ (ID) allocwithzone: (struct _nszone *) zone

{

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

_instace = [Super Allocwithzone:zone];

});

return _instace;

}

+ (Instancetype) Shareddatatool

{

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

_instace = [[Self alloc] init];

});

return _instace;

}

-(ID) Copywithzone: (Nszone *) zone

{

return _instace;

}

-(OneWay void) Release {

}

-(ID) retain {

return self;

}

-(Nsuinteger) Retaincount {

return 1;

}

-(ID) autorelease {

return self;

}

@end

V. Nsoperation and Nsoperationqueue

1. Types of queues

1> Home Row

* [Nsoperationqueue Mainqueue]

* Actions added to the "home column" will be placed in the main thread to execute

2> Non-Home row

* [[Nsoperationqueue alloc] init]

* Actions added to the "non-Home column" will be placed in the child thread execution

2. Queue Add Task

*-(void) Addoperation: (Nsoperation *) op;

*-(void) Addoperationwithblock: (void (^) (void)) block;

3. Common usage

1> Setting the maximum number of concurrent

-(Nsinteger) Maxconcurrentoperationcount;

-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;

2> Other operations on the queue

* Cancel All operations

-(void) cancelalloperations;

* Pause All operations

[Queue Setsuspended:yes];

* Restore all operations

[Queue Setsuspended:no];

4. Dependencies between operations (interview questions)

* Dependencies can be set between nsoperation to guarantee the order of execution

* [Operationb Adddependency:operationa];

Operation B depends on operation A, and operation A is performed before Operation B is performed.

* Note: cannot rely on each other, such as a dependent b,b dependency a

* You can create a dependency between nsoperation of different queue

5. Communication between threads

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

[Queue addoperationwithblock:^{

1. Perform some more time-consuming operations

2. Go back to the main thread

[[Nsoperationqueue Mainqueue] addoperationwithblock:^{

}];

}];

Vi. ways to return to the main thread from other threads

1.perform ...

[Self performselectoronmainthread:<# (SEL) #> withobject:<# (ID) #> waituntildone:<# (BOOL) #>];

2.GCD

Dispatch_async (Dispatch_get_main_queue (), ^{

});

3.NSOperationQueue

[[Nsoperationqueue Mainqueue] addoperationwithblock:^{

}];

Vii. Judging the compiler's environment: ARC or MRC?

#if __has_feature (OBJC_ARC)

The current compiler environment is arc

#else

The current compiler environment is MRC

#endif

Methods of initialization of classes

1.+ (void) load

* When a class is first mounted to the OC Runtime System (memory), it is called

* It will be called when the program starts

* The program will only be called 1 times during operation.

2.+ (void) Initialize

* When a class is first used (such as calling a method of a class), it invokes the

* Not called when a program starts

3. In the process of running the program: 1 classes of an operation, only want to execute 1 times, then this operation is placed in the + (void) Load method The most appropriate

IX. recommendations for the use of third-party frameworks

1. Purpose of the third-party framework

1> Development efficiency: rapid development, people wrapped up a line of code top of their own write n line

2> to use the best implementation of this feature

2. Excessive third-party frameworks, many disadvantages (negligible)

1> management, upgrades, updates

2> third-party framework has bugs waiting for the author to resolve

3> the author of a third-party framework unfortunately dies, stops updating (potential bug unsolved)

4> feeling: own good water

3. For example,

Stream media: Play online video, audio (side download side play)

Know the format of audio and video files very well

Each video has its own decoding method (c\c++)

4. Summary

1> standing on the shoulders of giants programming

2>, it's all right. Use a more stable third-party framework

MJ-0916-Multithreading 2

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.