This film revolves around multi-threading to fully unfold narrative.
1, why should have multi-threading/multithreading is used for what?
2. What is multithreading?
3, how to create multi-threading?
4, multi-threaded in which cases will use/multi-threaded use of the scene?
5, three kinds of multithreading advantages and disadvantages?
1, why should have multi-threading/multithreading is used for what?
Each IOS application has a main thread that is designed to update the UI interface and handle the user's touch events, so it is not possible to put other too-time-consuming operations on the main thread, or it will cause the main thread to clog (the phenomenon of card-machine), resulting in a very bad user experience. The general solution is to put those time-consuming operations into another thread to execute, multithreaded programming is the best way to prevent the main thread from clogging and increase the efficiency of the operation.
2. What is multithreading?
Multithreading is a complex concept, which, by definition, accomplishes multiple tasks synchronously and improves the efficiency of resource usage.
From the hardware, operating system, application software from different angles to see, multithreading has been given different connotations, for hardware, now on the market most of the CPU is multicore, multi-core CPU operation multithreading more excellent;
From the operating system point of view, is a multi-tasking, now using the mainstream operating system are multi-tasking, can listen to songs, while writing a blog;
For applications, multithreading allows the application to respond faster and respond to user touch actions while the network is downloading.
In the iOS application, the first understanding of multithreading is concurrency, it is the original meaning is to do water, then pick vegetables, and then stir-fry the work, will become boiling water to pick vegetables, and finally to stir-fry.
3, how to create multi-threading?
There are three ways to create a thread: Use Nsthread to create, use GCD dispatch, use a subclass nsoperation, and then add it to nsoperationqueue. Below are the three ways to do the detailed description:
1, create with Nsthread
There are two direct ways to create 1.1 Nsthread:
-(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument+ (void) Detachnewthreadselector: (SEL) Aselector Totarget: (ID) atarget withobject: (ID) anargument
Description: The first is an instance method and the second is a class method.
Selector: Thread execution method, this selector can only have one parameter, and cannot have return value
Target:selector object sent by message
Argument: The only parameter transmitted to target, or nil
The first way is to create the thread directly and start running the thread, the second way is to create the thread object before running the thread, and you can set thread information such as the thread priority before running the thread action.
PS: Methods that do not explicitly create threads:
Using the NSObject class method Performselectorinbackground:withobject: Create a thread: [OBJ performselectorinbackground: @selector ( dosomething) Withobject:nil];
2, using a subclass of Nsoperation
There are two ways to use nsoperation:
One is to use two defined subclasses: Nsinvocationoperation and Nsblockoperation.
#import "ViewController.h" #define Kurl @ "http://avatar.csdn.net/2/C/D/1_totogo2010.jpg" @interface Viewcontroller () @end @implementation Viewcontroller-(void) viewdidload {[Super viewdidload]; Nsinvocationoperation *operation = [[Nsinvocationoperation alloc]initwithtarget:self Selector: @selector (downloadimage:) Object:kurl]; Nsoperationqueue *queue = [[Nsoperationqueue alloc]init]; [Queue addoperation:operation]; Additional setup after loading the view, typically from a nib. }-(void) Downloadimage: (NSString *) url{NSLog (@ "url:%@", url); Nsurl *nsurl = [Nsurl Urlwithstring:url]; NSData *data = [[NSData Alloc]initwithcontentsofurl:nsurl]; UIImage * image = [[UIImage alloc]initwithdata:data]; [Self Performselectoronmainthread: @selector (UpdateUI:) withObject:image Waituntildone:yes]; }-(void) UpdateUI: (uiimage*) image{self.imageView.image = image; }
- You can see in the Viewdidload method that we built a background thread with nsinvocationoperation and put it in Nsoperationqueue. The background thread executes the Downloadimage method.
- The Downloadimage method handles the logic of downloading pictures. After the download is complete, use Performselectoronmainthread to execute the main thread UpdateUI method.
- UpdateUI and displays the downloaded picture in the picture control.
The other is inheriting nsoperation.
How do I control the number of threads in a thread pool?
Many nsoperation can be added to the queue, and nsoperationqueue can be thought of as a thread pool that adds operations (nsoperation) to the queue. Threads in a thread pool can be considered consumers, taken from a queue, and executed.
Set by the following code: [The number of threads in the queue setmaxconcurrentoperationcount:5];//thread pool, which is the number of concurrent operations. By default, -1,-1 represents no limit, which runs all the operations in the queue at the same time.
3, using GCD's dispatch
Create a serial dispatch queue (serial dispatch queue) with the Dispatch_queue_create function
Get Global concurrency Dispatch queue (concurrent dispatch queue) using the Dispatch_get_global_queue function
Use the Dispatch_get_main_queue function to get the serial dispatch queue associated with the application's main thread
Use the Dispatch_get_current_queue function for debugging purposes, or test the identity of the current queue. Calling this function in the Block object returns the queue to which the block was submitted (this time the queue should be executing). Calling this function outside of the block object returns the default concurrent queue for the app.
GCD Common methods:
1. Dispatch_async
To prevent the interface from being stuck in processing time-consuming operations, such as reading network data, IO, database reading and writing, we will process these operations in another thread and then notify the main thread to update the interface.
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{ //time-consuming Operation Dispatch_async ( Dispatch_get_main_queue (), ^{ //Update Interface });
2. Dispatch_group_async
Dispatch_group_async can be used to listen to whether a group of tasks are completed and be notified to perform other operations when completed. This method is useful, for example, you perform three download tasks, and when three tasks are downloaded, you are notified that the interface is complete.
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0); dispatch_group_t group = Dispatch_group_create (); Dispatch_group_async (group, queue, ^{ [Nsthread sleepfortimeinterval:1]; NSLog (@ "group1"); }); Dispatch_group_async (group, queue, ^{ [Nsthread sleepfortimeinterval:2]; NSLog (@ "group2"); }); Dispatch_group_async (group, queue, ^{ [Nsthread sleepfortimeinterval:3]; NSLog (@ "Group3"); }); Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{ NSLog (@ "UpdateUi"); }); Dispatch_release (group);
Dispatch_group_async is an asynchronous method that you can see when you run the print result:
2012-09-25 16:04:16.737 gcdtest[43328:11303] group12012-09-25 16:04:17.738 gcdtest[43328:12a1b] group22012-09-25 16:04:18.738 gcdtest[43328:13003] group32012-09-25 16:04:18.739 gcdtest[43328:f803] UpdateUi
Each second prints one, and when the third task executes, the UPADTEUI is printed.
3. Dispatch_barrier_async
Dispatch_barrier_async is executed after the execution of the previous task is completed, and the task after it is executed before it executes.
dispatch_queue_t queue = dispatch_queue_create ("Gcdtest.rongfzh.yc", dispatch_queue_concurrent); Dispatch_async (queue, ^{ [Nsthread sleepfortimeinterval:2]; NSLog (@ "dispatch_async1"); }); Dispatch_async (queue, ^{ [Nsthread sleepfortimeinterval:4]; NSLog (@ "Dispatch_async2"); }); Dispatch_barrier_async (queue, ^{ NSLog (@ "Dispatch_barrier_async"); [Nsthread sleepfortimeinterval:4]; }); Dispatch_async (queue, ^{ [Nsthread sleepfortimeinterval:1]; NSLog (@ "dispatch_async3"); });
Printing results:
2012-09-25 16:20:33.967 gcdtest[45547:11203] dispatch_async12012-09-25 16:20:35.967 gcdTest[45547:11303] Dispatch_ async22012-09-25 16:20:35.967 gcdtest[45547:11303] dispatch_barrier_async2012-09-25 16:20:40.970 gcdTest[ 45547:11303] Dispatch_async3
Note that the execution time can be seen in the order of execution as described above.
4. dispatch_apply
Executes a code fragment n times.
Dispatch_apply (5, Globalq, ^ (size_t index) { //executed 5 times});
4, multi-threaded in which cases will use/multi-threaded use of the scene?
In the network request, reads the massive file, the operation database, the massive data analysis, the Singleton, the delay and so on some time-consuming operation, will use the multithreading.
5, three kinds of multithreading advantages and disadvantages?
1. The advantage of Nsthread is that it is lighter and more intuitive to control threading objects than the other two multithreaded schemes. The disadvantage is that you need to manage the thread's life cycle, thread synchronization. Thread synchronization has a certain overhead in locking data.
2. The advantage of using nsoperation in a project is that Nsoperation is a highly abstract thread, which is used in the project to make the program structure of the project better, the sub-class nsoperation design idea, is the object-oriented advantages (multiplexing, encapsulation), The implementation is multithreaded support, and the interface is simple, it is recommended to use in complex projects. 3. The advantage of using GCD in a project is that the GCD itself is very simple and easy to use, saving code for uncomplicated multithreaded operations, and the use of block parameters is more readable and recommended for simple projects.
IOS interview frequently asked multi-threading