iOS Multithreading-Personal understanding

Source: Internet
Author: User

One, multi-threaded

Each IOS application has a main thread to update the UI interface, handle the user's touch events, and parse the data downloaded from the network, so it is not possible to put too much time-consuming operations (such as network download data) in the main thread, or it will cause the main thread to block (the interface is dead, prevent the interface to suspend animation), Bring a very bad user experience.

The solution for iOS is to put those time-consuming operations into another thread, and multithreaded asynchronous programming is the best way to prevent the main thread from clogging and increasing the efficiency of the operation.

Async: Multiple threads executing concurrently
Synchronization: Thread queuing execution
Parallel-"Asynchronous
Serial-"Sync


Multithreading Technology
1, asynchronous download data, is a more common application of multithreading technology scenario
2, multi-Threading Technology use scenario: The app has time-consuming operation or function (1, client and server interaction; 2) A single read of a large amount of data from the database 3, the parsing process of a large amount of data, need to open a new thread (child thread/worker thread) outside the main thread to execute


The multithreaded programming methods supported by iOS:

Nsthread

Nsoperation & Nsoperationqueue

GCD


1. How to create a thread
A.
Create a thread but this thread does not automatically execute
Nsthread *t = [[Nsthread alloc] initwithtarget:self selector: @selector (threadMain1:) object:n];
Start running thread manually open
[t start];
B.
The thread will run automatically when it is created
[Nsthread detachnewthreadselector: @selector (threadMain0:) totarget:self withobject:n];

2. Animation of the interface
The main thread downloading data will cause the interface card to die


3. Listener Thread End
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (threadExit:) Name: Nsthreadwillexitnotification Object:nil];

4. Communication between multiple threads

[T0 cancel];
if ([t iscancelled]) {...}
Exit/End Thread
[Nsthread exit]; or a return;

5. Thread Lock
Nslock Mutual Exclusion Lock
Avoid multiple threads modifying the same resource at the same time

Modify the database notation

6. Thread Modification Progress bar

UI main thread Refresh UI interface
[Self Performselectoronmainthread: @selector (Refreshui:) withobject:@ (i) waituntildone:no];

Dispatch_async (Dispatch_get_main_queue (), ^{
[Self refreshui:1];
});
Nsinvocationoperation *operation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (updateimage :) Object:image];
[[Nsoperationqueue Mainqueue] addoperation:operation];

What is the main thread? Everything that is not in normal/worker threads is in the main thread of the UI

7. Custom Threads
A custom thread to inherit with Nsthread

Need to implement-main thread principal function



Extension functions
Gets the current thread
+ (Nsthread *) CurrentThread;
Creating a Startup Thread
+ (void) Detachnewthreadselector: (SEL) selector totarget: (ID) target withobject: (id) argument;
Determine if it is multithreaded
+ (BOOL) ismultithreaded;

-(Nsmutabledictionary *) threaddictionary;
Thread sleep NSDate give a sleep to when
+ (void) Sleepuntildate: (NSDate *) date;
Thread Sleep Time
+ (void) Sleepfortimeinterval: (Nstimeinterval) ti;
End/Exit Current thread
+ (void) exit;
Gets the current thread priority
+ (double) threadpriority;
Sets the priority of the current thread generally we do not set
The thread priority that you create yourself is 0.5 The main thread is about 0.8
Priority returns 0---1.0
Setting the priority level
+ (BOOL) SetThreadPriority: (double) p;
Gets the priority of the specified thread
-(double) threadpriority ns_available (10_6, 4_0);
-(void) SetThreadPriority: (double) p ns_available (10_6, 4_0);

Set the name of the thread
-(void) SetName: (NSString *) n ns_available (10_5, 2_0);
-(NSString *) name ns_available (10_5, 2_0);

Determines whether the specified thread is the main path
-(BOOL) Ismainthread ns_available (10_5, 2_0);
Determines whether the current thread is the main path
+ (BOOL) ismainthread ns_available (10_5, 2_0); Reports whether current thread is main
Get the main thread
+ (Nsthread *) Mainthread ns_available (10_5, 2_0);

-(ID) init ns_available (10_5, 2_0); Designated initializer
-(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument ns_available (10_5, 2_0);
Specifies whether the thread is executing
-(BOOL) isexecuting ns_available (10_5, 2_0);
Whether the thread is complete
-(BOOL) isfinished ns_available (10_5, 2_0);
Whether the thread has been canceled (signaled to the current thread)
-(BOOL) iscancelled ns_available (10_5, 2_0);
Whether the end thread of the sending thread cancels the signal is determined by the thread itself
-(void) Cancel ns_available (10_5, 2_0);
Start thread
-(void) Start ns_available (10_5, 2_0);

The functions that are executed in the thread's main function are called in the-main function.
-(void) main ns_available (10_5, 2_0); Thread Body Metho






second, the task queue

Nsoperation

Nsthread the most basic class of operating threads, the resulting child threads are less efficient than nsoperation
Nsoperation is a lightweight thread

Nsoperationqueue thread pool, Operation queue

A task-oriented management threading mechanism that puts operations (tasks) into the thread pool, automatically executes and weakens the concept of threading. (Task: Can be considered a thread)

Custom tasks

Nsoperation abstract class, if you want to create your own task, you should inherit nsoperation, to implement your own class
Rewrite the main function!


Third, GCD (official recommendation)
GCD full name Grand Central Dispatch (queue scheduling)

is a set of low-level APIs that provide a new way to get into the programming of concurrent programs.
From the basic function, GCD is a bit like nsoperationqueue, they all allow the program to split the task into multiple single tasks, and then submit? to the work queue to hold the line concurrently or in a row.

GCD is the C implementation,? Nsopertionqueue is more efficient at the bottom, and it's not part of the cocoa framework
Concurrent tasks are based on the load of the system as nsoperationqueue as appropriate, and the string row queue only performs a single task at the same time
GCD's API is largely based on block

1. Main thread Queue
The main thread queue internal execution task is a serial synchronous operation
The main thread queue does not need to be created by the Dispatch_get_main_queue () method to obtain
dispatch_queue_t queue = Dispatch_get_main_queue ();
Dispatch_async (Queue, ^{
[Self taskThread1];
});
Or
Dispatch_async (Dispatch_get_main_queue (), ^{
[Self taskThread2];
});


2. Create a private queue user queue/serial queue
C interface, create a private queue, queue name is a C string, no special requirements, Apple recommends using Flip identifier (the name, more for debugging)
Inside the private queue is also a serial operation
dispatch_queue_t queue = dispatch_queue_create ("Com.qianfeng", NULL);

Dispatch_async (Queue, ^{
[Self taskThread2];
});
We create ourselves a queue that we need to destroy ourselves
Dispatch_release (queue);
Non-arc needs to be destroyed



3. Global queue
Parallel queues (global) do not need to be created by Dispatch_get_global_queue () method to obtain
Three available queues
The first parameter is to select a global queue, typically with default,
The second parameter is a reserved flag, and the current version is not useful (not for future versions), and is set to 0 directly.
Dispatch_queue_priority_high
Dispatch_queue_priority_default
Dispatch_queue_priority_low
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);


Frequently used: Add blocks (data download, file operations, database Operations) in the global queue to refresh the UI in the main queue (refresh the UI, be sure to do it on the main thread)

The loop of the Nsrunloop event is the core of an iOS program that implements asynchronous event processing, each of which is controlled by a loop
Currentrunloop gets the loop that controls the current thread, maintains the active state of the current thread through the loop, pauses the current thread until the data download is complete
while (!_isdone) {
Thread will block
[[Nsrunloop Currentrunloop] rununtildate:[nsdate Distantfuture]];
NSLog (@ "mission");
When the download is complete, another download thread notifies the current thread, and the current thread comes to the input source, and Nsrunloop exits
};//Only if the download is complete this will nsrunloop the actual exit or otherwise make Nsrunloop exit _isdone not yes then Nsrunloop will continue to run

iOS Multithreading-Personal understanding

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.