This article reprinted to http://blog.csdn.net/davidsph/article/details/8171607
iOS is multi-threaded and generally divided into three different ways:
1,thread;
2, COCOA operations;
3, Grand Central Dispatch (GCD) (iOS4 only start to support)
Here's a quick explanation:
1:nsthread
There are two main ways of creating:
[Nsthread detachnewthreadselector: @selector (mythreadmainmethod:) totarget:self Withobject:nil];
And
nsthread* myThread = [[Nsthread alloc] Initwithtarget:self
Selector: @selector (mythreadmainmethod:)
Object:nil];
[MyThread start]; Start thread
The difference between the two approaches is that the first call creates a thread to do the work immediately, and the second one, although you alloc init, will not actually create the thread until we manually invoke start to start the thread. This idea of deferred implementation is useful in many resources-related areas. The latter way we can also configure the thread before starting the thread, such as setting the stack size, thread priority.
In addition, there is an indirect way: the use of NSObject method
Performselectorinbackground:withobject: To create a thread:
[MYOBJ performselectorinbackground: @selector (Mythreadmainmethod) Withobject:nil]; Run a method in the background
The effect is the same as Nsthread's detachNewThreadSelector:toTarget:withObject: the same.
2,nsoperation:
The official explanation: the Nsoperation class is an abstract class encapsulate, the code and data associated with a single task. Because It is abstract, you do not use this class directly but instead subclass or use one of the system-defined Subclasse S (nsinvocationoperation or nsblockoperation) to perform the actual task.
Concurrent execution you need to overload the following 4 methods
Execute the task main function, the entry function that the thread runs
-(void) Start
Whether to allow concurrency, return yes, allow concurrency, return no not allowed. Default returns NO
-(BOOL) isconcurrent
-(BOOL) isexecuting
Whether it has been completed, this must be overloaded, or put in the nsoperationqueue in the nsopertaion can not be released normally.
-(BOOL) isfinished
For example, Testnsoperation:nsoperaion overloads the above 4 methods,
Declare a nsoperationqueue,nsoperationqueue *queue = [[[Nsoperationqueue alloc] init]autorelease];
[Queue addoperation:testnsoperation];
It will automatically call the Start function in Testnsoperation, if you need more than one nsoperation, you need to set some properties of the queue, if there is a dependency between multiple nsoperation, you can also set, you can refer to the API documentation.
(2) Non-concurrent execution
-(void) Main
You just need to overload the main method.
3, GCD
Dispatch_async (dispatch_queue_t queue,dispatch_block_t block);
Async indicates that the block represents the thing you want to do asynchronously, and the queue is the one who handles the task.
Multithreading is used in programs because the program often needs to read the data and then update the UI. For a good user experience, reading data will tend to run in the background to avoid blocking the main thread. There are three kinds of queue to deal with in GCD.
1. Main Queue:
As the name implies, it runs on the main thread and is obtained by Dispatch_get_main_queue. UI related to using Mainqueue.
2.Serial Quque (Private dispatch queue)
Each time you run a task, you can add multiple, execution order FIFO. Usually refers to a programmer-generated.
3. Concurrent Queue (Globaldispatch queue):
You can run multiple tasks at the same time, each of which depends on the order in which the queue is joined, and on the sequence in which it ends. obtained using Dispatch_get_global_queue.
So we can get a general idea of the framework using GCD:
1 2 3 4 5 6 7 |
Dispatch_async (getdataqueue,^{ After getting the data, get a group and refresh the UI. DISPATCH_AYSNC (Mainqueue, ^{ UI updates need to be made in the main thread }; } ) |
Here's how to summarize the differences between the three ways of multithreading:
Thread is relatively lightweight in these three paradigms, but is also the most responsible for the use, you need to manage the thread's life cycle, synchronization between threads. Threads share part of the memory space of the same application, and they have the same access rights to the data. You have to coordinate the access of multiple threads to the same data, and the general practice is to lock them before access, which can lead to some performance overhead. In IOS we can use several forms of thread:
Cocoa Threads: Use Nsthread or directly from the NSObject class method Performselectorinbackground:withobject: To create a thread. If you choose thread to implement multi-threading, then nsthread is the preferred way to use the official recommendation.
Cocoa operations is implemented based on OBECTIVE-C, and class nsoperation encapsulates what the user needs to do in an object-oriented manner, so we focus on what we need to do, without worrying too much about thread management, synchronization, etc. Because Nsoperation has encapsulated these things for us. Nsoperation is an abstract base class, and we must use its subclasses. Two default implementations of IOS are available: Nsinvocationoperation and nsblockoperation.
Grand Central Dispatch (GCD): IOS4 only started to support, it provides some new features, and the runtime to support multicore parallel programming, with a higher focus: how to increase efficiency on multiple CPUs.
Finally, since said multi-threaded development, will inevitably be in the multi-threaded communication;
Using some of the NSObject's class methods, it can be easily done.
Do things in the main thread of the application:
-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait
-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) Wait modes: (Nsarray *) Array
To do something in the specified thread:
-(void) Performselector: (SEL) aselector onthread: (Nsthread *) THR Withobject: (ID) arg waituntildone: (BOOL) wait
-(void) Performselector: (SEL) aselector onthread: (Nsthread *) THR Withobject: (ID) arg waituntildone: (BOOL) wait modes: ( Nsarray *) array
Do things in the current thread:
Invokes a method of the receiver on the current thread, using the default mode after a delay.
-(void) Performselector: (SEL) Aselector withobject: (ID) anargument afterdelay: (nstimeinterval) delay
PerformSelector:withObject:afterDelay:inModes:
Cancels a message sent to the current thread
Cancelpreviousperformrequestswithtarget:
CancelPreviousPerformRequestsWithTarget:selector:object:
such as when we download data in a thread, after the download is complete to notify the main thread of the update interface, etc., you can use the following interface:-(void) Mythreadmainmethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
To does something in your thread job
...
[Self Performselectoronmainthread: @selector (UpdateUI) Withobject:nil Waituntildone:no];
[Pool release];
}
Multi-threaded learning, is a continuous process of progress together to learn together. In the future, we should pay more attention to the use of GCD, because it is closely related to block, it will be a future trend.