iOS multithreaded operations

Source: Internet
Author: User

The concept of multi-threading

 Process

  · A running program is a process that is responsible for the memory allocation that the program runs  

• No process has its own independent virtual memory space

 Thread

  • A thread is a separate execution path in a process, also known as a control unit

• A process contains at least one thread, and the main thread

• Time-consuming execution paths such as network requests can be executed in other threads

 The purpose of creating a thread is to open a new execution path, run the specified code, and execute concurrently with the code implementation in the main thread

Also explain a concept: multi-tasking scheduling system

Each application is allocated by the operating system for a short period of time (TimeSlice) in turn using the CPU, because the CPU to each time slice processing speed very fast, therefore, the user appears as if these tasks are executed at the same time

Concurrency: Refers to two or more tasks that occur at the same time interval, but at any point the CPU performs only one task.

 How iOS multithreading is implemented:

1.NSObject Multithreading Technology

1> want to open a new thread in a method can call the Performselectorinbackground method directly to open, the method in selector is to perform the operation

2> use Performselectoronmainthread can return to the main thread, the operation of the UI to go back to the main line approached (Official rules, if not to do so is likely to have unforeseen problems)

3> in order to simulate the creation of threads, the use of thread hibernation here is simulated, equivalent to the operation of a network request

Mark: Although the UI can still be changed in other threads, it's strongly not recommended! Another important issue is that thread operations using Nsthread and NSObject use Autoreleasepool, or memory leaks occur

1- (void) Viewdidload2 {3 [Super Viewdidload];4     //use Performselectorinbackground to open a background thread and perform the method chosen by the selector selector5     //2> uses Performselectoronmainthread to go back to the main thread to perform tasks, typically used when the background thread updates the interface UI6     //Note: When using Nsthread or NSObject threading methods, be sure to use the auto-free pool, otherwise memory leaks are prone to occur. 7     //tip: Using Performselectorinbackground can also modify the UI directly, but it is strongly not recommended. Modifying the UI is best done in the main thread8 [Self performselectorinbackground: @selector (Testobject) Withobject:nil];9     TenNSLog (@"%@", [Nsthread CurrentThread]); One } A  --(void) Testobject - { the     //automatically frees up the pool to avoid memory leaks - @autoreleasepool { -         //let the current thread sleep 2s -[Nsthread Sleepfortimeinterval:2.0f]; +          -NSLog (@"%@", [Nsthread CurrentThread]); +     } A}
View Code

  2.NSThread Threading Methods

1. Direct generation of new thread invocation methods through the class method: Detachnewthreadselctor, automatic execution of methods in Selector

2. Using the instance method to generate a new thread call to the Initwithtarget method, you need to invoke the instance's Start method to execute the Selector method

3.NSThread also needs to use Autoreleasepool for memory management

+ View Code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 - (void)viewDidLoad {     [super viewDidLoad];     //NSThread类方法开启线程 //    [NSThread detachNewThreadSelector:@selector(testThread) toTarget:self withObject:nil];     //实例方法开启线程     NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(testThread) object:nil];     //调用start方法才能执行selector的方法     [thread start];     NSLog(@"%@",[NSThread currentThread]); }-(void)testThread {     @autoreleasepool {         //线程休眠,模拟耗时操作         [NSThread sleepForTimeInterval:2.0f];                 NSLog(@"%@",[NSThread currentThread]);     } }

  3. Using Nsoperation for multithreading

1. The first way to implement multithreading

(1) Create a new queue to store the required operations

(2) Create a new instance of Nsinvocationopertaion to store an operation

(3) Add the new operation to the newly created queue to perform the operation in accordance with the first-in-a-out features of the team

  

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 @interface SWBViewController () {     NSOperationQueue *_queue; } @end@implementation SWBViewController- (void)viewDidLoad {     [super viewDidLoad];          NSLog(@"%@",[NSThread currentThread]);         //1初始化队列     _queue = [[NSOperationQueue alloc]init];         //2创建线程     NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testObject) object:nil];     //3开启线程     [_queue addOperation:op];     // Do any additional setup after loading the view, typically from a nib. }- (void)testObject { //    [NSThread sleepForTimeInterval:2.0f];     NSLog(@"%@",[NSThread currentThread]); }

  2. Using Nsblockoperation for multithreaded operations

(1) Create a queue to store the actions that need to be performed

(2) Create a new block code operation using [Nsblockoperation Blockoperationwithblock] to store code that needs to be executed inside the fast code

(3) put block code operations into the queue to perform the same FIFO operation

#mark Nsoperation is a set of OBJECTIVE-C APIs implemented using GCD and is an object-oriented threading technology that provides some additional ways to facilitate operations

(1)[nsopeationqueue mainqueue] addoperation ^{};//Update UI main queue operations in fast code execution

(2)setmaxconcurrentoperationcount;//set the maximum number of concurrent threads

(3) Set dependencies between threads Adddependency can set the order in which tasks are executed, and can specify dependencies across operation queues (specifies that dependencies cannot be specified in a loop)

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @interface SWBViewController () {     NSOperationQueue *_queue; } @end@implementation SWBViewController- (void)viewDidLoad {     [super viewDidLoad];          NSLog(@"%@",[NSThread currentThread]);         //1初始化队列     _queue = [[NSOperationQueue alloc]init];     //    //2创建线程 //    NSInvocationOperation *op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(testObject) object:nil];     NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{         // 让当前线程睡眠 2.0 秒         [NSThread sleepForTimeInterval:2.0f];         NSLog(@"%@",[NSThread currentThread]);     }];     //3开启线程     [_queue addOperation:op];     // Do any additional setup after loading the view, typically from a nib. }

  

4.GCD Multithreading Technology

(1) is a C-based underlying API

(2) Use block to define task flexibility and ease of use

(3) provides additional control capabilities and underlying functions that are not available in the Operation queue

GCD The basic idea is to put operations in the queue to execute

1. Operation using block definition

2. The queue is responsible for scheduling the thread on which the task executes and the specific execution time

3. The team is characterized by first-out, the newly added operation will be in the tail.

 

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.