Understanding the development of IOS multi-threaded applications and how to create threads _ios

Source: Internet
Author: User
Tags reserved

One, processes, and threads
1. What is a process

A process is an application that is running in the system
Each process is independent, with each process running in its dedicated and protected memory space

For example, open QQ, Xcode at the same time, the system will start 2 processes separately
You can view the processes that are open on your Mac system through Activity Monitor

2. What is a thread
1 processes must have a wired thread (at least 1 threads per 1 process) to perform a task
Threads are the basic unit of execution for a process, and all tasks of a process (program) are executed in threads
such as the use of cool dogs to play music, the use of thunder to download movies, all need to execute in the thread

3. Serial of Threads

The execution of a task in 1 threads is serial
If you want to perform multiple tasks in 1 threads, you can perform these tasks sequentially in one place
That is, at the same time, 1 threads can only perform one task
For example, download 3 files in 1 threads (file A, file B, file C, respectively)

Second, multithreading

1. What is multithreading
More than one thread can be opened in 1 processes, and each thread can perform different tasks in parallel (while)
Process-> Workshop, thread-> workshop worker
Multithreading technology can improve the execution efficiency of programs
For example, open 3 threads at the same time download 3 files separately (file A, file B, file C, respectively)

2. The principle of multithreading

At the same time, the CPU can handle only 1 threads, and only 1 threads are working (executing)
Multithreading concurrency (simultaneous) execution, in fact, is the CPU quickly between multiple threads scheduling (switching)
If the CPU schedules the thread fast enough, it creates the illusion of concurrent execution of multithreading
Thinking: What happens if the thread is very, very much?
CPU in the n multithreading between the scheduling, the CPU will be exhausted, consuming a lot of CPU resources
The frequency at which each thread is scheduled to execute is reduced (the execution efficiency of the thread is reduced)

3. Multithreading Advantages and disadvantages

The advantages of multithreading
Can improve the execution efficiency of the program properly
can improve resource utilization (CPU, memory utilization) appropriately

The disadvantages of multithreading
Opening a thread requires a certain amount of memory space (by default, the main thread occupies 1M, child threads occupy 512KB), if a large number of threads, will occupy a large amount of memory space, reduce the performance of the program
The more threads, the higher the CPU's overhead on the scheduling thread
Programming is more complex: for example, communication between threads, multi-threaded data sharing

4. Multithreading in the development of iOS applications
Main thread: After an iOS program runs, the default will open 1 threads, called "Main thread" or "UI thread"
Main role of the primary thread
Display \ Refresh UI interface
Handle UI events (such as click events, scrolling events, drag events, and so on)


The use of the main thread note: Do not put more time-consuming operations into the main thread.
Time-consuming operations will hold the main thread, seriously affecting the fluency of the UI, giving users a bad experience of "card"

5. code example

Copy Code code as follows:

//
Yyviewcontroller.m
01-Block Main thread
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYViewController.h"

@interface Yyviewcontroller ()
-(ibaction) Btnclick;
@end


Copy Code code as follows:

@implementation Yyviewcontroller


-(void) viewdidload
{
[Super Viewdidload];
}


Click event for button
-(ibaction) Btnclick {
1. Get current thread
Nsthread *current=[nsthread CurrentThread];
2. Perform some time-consuming operations with a for loop
for (int i=0; i<10000; i++) {
3. Output thread
NSLog (@ "Btnclick---%d---%@", i,current);
}
}

@end


Execution effect:

Description: When the click Executes, TextView clicks no response.

Perform analysis: Waits for the main thread to execute serially.

Opens the child thread.

Three, create and start a thread simple description
a Nsthread object represents a thread

Create, start a thread

(1)

Copy Code code as follows:
Nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (run) Object:nil];

[Thread start];

When a thread starts, it executes the self's Run method in thread thread


Main thread related usage

Copy Code code as follows:

+ (Nsthread *) Mainthread; Get the main thread

-(BOOL) Ismainthread; is the main thread

+ (BOOL) Ismainthread; is the main thread



Other usage

Get current thread

Copy Code code as follows:

Nsthread *current = [Nsthread CurrentThread];

Scheduling priority of a thread: the range of scheduling priority is 0.0 ~ 1.0, the default 0.5, the higher the value, the greater the priority

Copy Code code as follows:

+ (double) threadpriority;

+ (BOOL) SetThreadPriority: (double) p;


Set the name of the thread

Copy Code code as follows:

-(void) SetName: (NSString *) n;

-(NSString *) name;


Other ways to create threads
(2) automatically start the thread after creating the thread [Nsthread detachnewthreadselector: @selector (Run) totarget:self Withobject:nil];
(3) implicitly create and start a thread [self performselectorinbackground: @selector (Run) Withobject:nil];
The advantages and disadvantages of the above 2 thread creation methods
Advantages: Simple and quick
Disadvantage: Unable to set more details on the thread

Four, multithreaded code example

1. Use ancient ways to create

Copy Code code as follows:

//
Yyviewcontroller.m
//
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//


#import "YYViewController.h"
#import <pthread.h>


@interface Yyviewcontroller ()
-(ibaction) Btnclick;
@end

@implementation Yyviewcontroller

-(void) viewdidload
{
[Super Viewdidload];
}


Click event for button
-(ibaction) Btnclick {
1. Get current thread
Nsthread *current=[nsthread CurrentThread];
Main thread
NSLog (@ "Btnclick----%@", current);

2. Perform some time-consuming operations with a for loop
pthread_t thread;
Pthread_create (&thread, NULL, run, NULL);
}


C language function
void *run (void *data)
{
Gets the current thread, which is the newly created thread
Nsthread *current=[nsthread CurrentThread];


for (int i=0; i<10000; i++) {
NSLog (@ "Btnclick---%d---%@", i,current);
}
return NULL;
}

Multiple threads, click the button to execute the button to invoke the method, the main thread is not blocked

@end


Implementation effect:

Print results:

2. Create a thread using Nsthread

Copy Code code as follows:

//
Yyviewcontroller.m
//
//
Created by Apple on 14-6-23.
Copyright (c) 2014 itcase. All rights reserved.
//

#import "YYViewController.h"
#import <pthread.h>


@interface Yyviewcontroller ()
-(ibaction) Btnclick;
@end


Copy Code code as follows:

@implementation Yyviewcontroller

-(void) viewdidload
{
[Super Viewdidload];
}


Click event for button
-(ibaction) Btnclick {
1. Get current thread
Nsthread *current=[nsthread CurrentThread];
Main thread
NSLog (@ "Btnclick----%@", current);

Another way to get the main thread
Nsthread *main=[nsthread Mainthread];
NSLog (@ "main thread-------%@", main);

2. Perform some time-consuming operations
[Self creatnsthread];
[Self creatNSThread2];
[Self creatNSThread3];
}


/**
* Nsthread Create thread mode 1
* 1> first create the initialization thread
* 2> Start opening thread
*/
-(void) Creatnsthread
{
Nsthread *thread=[[nsthread alloc]initwithtarget:self selector: @selector (run:) object:@ "thread A"];
Set a name for the thread
thread.name=@ "Thread A";
Open Thread
[Thread start];

Nsthread *thread2=[[nsthread alloc]initwithtarget:self selector: @selector (run:) object:@ "thread B"];
Set a name for the thread
thread2.name=@ "Thread B";
Open Thread
[Thread2 start];
}


/**
* Nsthread Create thread mode 2
* Create thread Direct (automatic) Start
*/

-(void) creatNSThread2
{
Nsthread *thread=[nsthread detachnewthreadselector: @selector (run:) totarget:self withobject:@ "Create thread Direct (automatic) start"];

[Nsthread detachnewthreadselector: @selector (run:) totarget:self withobject:@ "Create thread Direct (automatic) start"];
}


/**
* Nsthread Create thread mode 3
* Create threads implicitly, and start directly (automatically)
*/

-(void) creatNSThread3
{
Executing in a background thread = = = Executing in a child thread
[Self Performselectorinbackground: @selector (run:) withobject:@ "implicitly created"];
}

-(void) Run: (NSString *) str
{
Get current thread
Nsthread *current=[nsthread CurrentThread];
Print output
for (int i=0; i<10; i++) {
NSLog (@ "Run---%@---%@", current,str);
}
}
@end


Call Thread 1, print the result:

Call Thread 2

Call Thread 3

Related Article

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.