Multithreading in ios development

Source: Internet
Author: User

Multithreading is mainly used to perform some time-consuming operations, such as downloading resources such as network images, videos, songs, books, and playing music in the game. It gives full play to the advantages of multi-core processors, concurrent (simultaneous execution) tasks allow the system to run faster and smoother. This section describes the commonly used multithreading technologies, including NSObject, NSThread, NSOperation, and GCD. 1. NSObject multithreading technology 1> you can use javasmselectorinbackground to enable background threads and run the selector selection method 2> Use javasmselecw.mainthread to return to the main thread to execute tasks, generally, it is used when the background thread updates the UI by using 3> [NSThread sleepForTimeInterval: 1.0f]; To sleep the current thread, which is usually used in program development to simulate time-consuming operations, this allows you to track different concurrent executions! However, do not retain this method when the program is released! Do not give the code in the test to the customer. Otherwise, the user experience may be poor. Tip: You can use javasmselectorinbackground to directly modify the UI, but it is strongly not recommended. It is best to modify the UI in the main thread. Note: when using the NSThread or NSObject thread method, you must use the automatic release pool. Otherwise, memory leakage may occur. Copy code 1-(void) viewDidLoad 2 {3 [super viewDidLoad]; 4 5 // Method 6 of thread execution in the background [self defined mselectorinbackground: @ selector (testObject) withObject: nil]; 7 8 // print the current thread num 9 NSLog (@ "main-% @", [NSThread currentThread]); 10} 11 12-(void) testObject13 {14 // automatically release the pool to avoid Memory leakage 15 @ autoreleasepool {16 17 // sleep the current thread for 2.0 seconds 18 [NSThread sleepForTimeInterval: 2.0f]; 19 20 // print the current thread 21 NSLog (@ "Background-% @", [NSThread CurrentThread]); 22} 23} copy Code 2, NSThread multithreading technology 1> class method directly enable the background thread, and execute the selector method detachNewThreadSelector 2> member method, after instantiating the thread object, you need to use the start execution selector method initWithTarget for simple use of NSThread. You can use NSObject's javasmselectorinbackground to replace it. In the NSThread call method, you also need to use autoreleasepool for memory management, otherwise, memory leakage may occur. Copy code 1-(void) viewDidLoad 2 {3 [super viewDidLoad]; 4 5 // enable the new thread execution method 6 [NSThread detachNewThreadSelector: @ selector (testObject) toTarget: self withObject: nil]; 7 8 /// enable task 9 by instantiating a thread // NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (testObject) object: nil]; 10 // 11 // [thread start]; 12 13 // print the current thread num14 NSLog (@ "main-% @", [NSThread currentThread]); 15} 16 17-(voi D) testObject18 {19 // automatically release the pool to avoid Memory leakage 20 @ autoreleasepool {21 22 // sleep the current thread for 2.0 seconds 23 [NSThread sleepForTimeInterval: 2.0f]; 24 25 // print the current thread 26 NSLog (@ "Background-% @", [NSThread currentThread]); 27} 28} copy code 3. NSOperation multithreading technology 1> usage steps: 1) instantiation operation a) NSInvocationOperation B) NSBlockOperation 2) Add the operation to the queue NSOperationQueue to start multi-thread execution 2> Update the UI using the main thread queue [NSOpeationQueue mainQueue] addOperation ^ {}; 3> setMaxConcu of the operation queue RrentOperationCount can be used to set the number of concurrent threads! Tip: this function is available only for NSOperation! 4> using addDependency, you can set the execution sequence of tasks and specify dependencies across operation queues. Note: When specifying dependencies, do not cycle dependencies; otherwise, do not run. Copy code 1 @ interface FLViewController () 2 {3 NSOperationQueue * _ queue; 4} 5 @ end 6 7 @ implementation FLViewController 8 9-(void) viewDidLoad10 {11 [super viewDidLoad]; 12 13 // 1. initialize the operation queue 14_queue = [[NSOperationQueue alloc] init]; 15 16 // 2. create thread operation 17 // NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (testObject) object: nil]; 18 19 NSBlockOperation * Op = [NSBlockOperation blockOperationWithBlock: ^ {20 21 // set the current thread to sleep for 2.0 seconds 22 [NSThread sleepForTimeInterval: 2.0f]; 23 24 // print the current thread 25 NSLog (@ "Background-% @", [NSThread currentThread]); 26}]; 27 // 3. open thread 28 [_ queue addOperation: op]; 29} copy code 4, GCD multithreading technology-Grand Central Dispatch GCD is based on the C language framework, this multithreading technology is officially recommended by Apple. 1> to use GCD, all methods start with dispatch 2> glossary global queue async asynchronous sync 3> to execute asynchronous tasks, run the dispatch_async command in the global queue to control the asynchronous execution of dispatch_async. 4> about the global queue dispatch_get_global_queue parameter of the GCD queue: the priority queue is always 0 ", DISPATCH_QUEUE_SERIAL); it is created and cannot be directly obtained from the master column dispatch_get_main_queue 5> asynchronous and synchronous are not related to the method name, and are related to the queue where the operation is located! Tip: to be familiar with the synchronization and asynchronous running of queues, you must write your own code to test it! Rule: The concurrency Queue (global/concurrent) determines whether it is synchronous execution (dispatch_sync) or asynchronous execution (dispatch_async) serial Queue (serial) based on the function name ), whether synchronous or asynchronous, all functions follow synchronous execution. If the first function in the queue is synchronous, all functions in the queue are executed in the current thread (generally the main thread ).

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.