Home>

Processes and threads1. What is a process

A process is an application that is running in the system

Each process is independent,Each process runs in its dedicated and protected memory space

For example, open qq and xcode at the same time, the system will start 2 processes separately

"Activity Monitor" can view the processes started in the mac system

2. What is a thread

If a process wants to perform a task,Must have threads (at least 1 thread per process)

A thread is the basic unit of execution of a process.All tasks of a process (program) are performed in threads

Such as playing music with cool dogs, downloading movies with Thunder,Both need to be executed in a thread

3. Serialization of threads

Task execution in 1 thread is serial

If i want to perform multiple tasks in 1 thread,Then you can only perform these tasks one by one in order

That is,At the same time,1 thread can only execute 1 task

For example, download three files in one thread (file a, file b, and file c)

Second, multi-threaded

1. What is multithreading

Multiple threads can be started in a process,Each thread can perform different tasks in parallel (simultaneously)

Process->workshop, thread->workshop worker

Multi-threading technology can improve program execution efficiency

For example, open three threads and download three files (file a, file b, and file c).

2. The principle of multithreading

at the same time,cpu can only handle 1 thread, only 1 thread is working (executing)

Multi-threaded concurrent (simultaneous) execution is actually a cpu to quickly schedule (switch) between multiple threads

If the CPU schedules the thread fast enough,Creates the illusion of multi-threaded concurrent execution

Thinking:If there are very many threads,What will happen?

cpu will be scheduled between n multiple threads,CPU will be exhausted and consume a lot of CPU resources

Each thread is scheduled to be executed less frequently (the execution efficiency of the thread is reduced)

3. Pros and cons of multithreading

Advantages of multithreading

Can appropriately improve the efficiency of program execution

Can appropriately increase resource usage (cpu, memory usage)

Disadvantages of multithreading

Starting threads requires a certain amount of memory space (by default,The main thread occupies 1m and the child threads occupy 512kb). If a large number of threads are started,Will take up a lot of memory space,Degraded program performance

The more threads,The greater the CPU's overhead on scheduling threads

Programming is more complicated:such as communication between threads, multi-threaded data sharing

4. Application of multithreading in ios development

Main thread:After an ios program runs,1 thread is enabled by default, called "main thread" or "ui thread"

The main role of the main thread

Show \ refresh ui interface

Handle ui events (such as click events, scroll events, drag events, etc.)

Use of the main thread Note:Do not put time-consuming operations in the main thread.

Time-consuming operations can jam the main thread,Seriously affects the smoothness of ui,Give users a "card" bad experience

5. Code example

//
//yyviewcontroller.m
//01- Block the main thread
//
//created by apple on 14-6-23.
//copyright (c) 2014 itcase. all rights reserved.
//
</p>
<p>
#import "yyviewcontroller.h"
</p>
<p>
@interface yyviewcontroller ()
-(ibaction) btnclick;
@end

@implementation yyviewcontroller
</p>
<p>
-(void) viewdidload
{
 [super viewdidload];
}
</p>
<p>
//button click event
-(ibaction) btnclick {
 //1. Get the current thread
 nsthread * current=[nsthread currentthread];
 //2. Use a for loop to perform some time-consuming operations
 for (int i=0;i<10000;i ++) {
 //3. Output thread
 nslog (@ "btnclick ---%d ---%@", i, current);
 }
}
</p>
<p>
@end

Implementation effect:

Note:When you click to execute,Textview clicks are not responding.

Execution analysis:wait for the main thread to execute serially.

Start child threads.

Simple instructions for creating and starting threadsA nsthread object represents a thread

Create and start threads

(1)

nsthread * thread=[[nsthread alloc] initwithtarget:self selector:@selector (run) object:nil];
</p>
<p>
[thread start];
</p>
<p>
//Once the thread is started,Will execute the run method of self in the thread

Main thread related usage

+ (nsthread *) mainthread;//get main thread
</p>
<p>
-(bool) ismainthread;//whether the main thread
</p>
<p>
+ (bool) ismainthread;//whether the main thread

Other uses

Get the current thread

nsthread * current=[nsthread currentthread];

Thread scheduling priority:The scheduling priority ranges from 0.0 to 1.0. The default value is 0.5. The larger the value, the higher the priority.

+ (double) threadpriority;
</p>
<p>
+ (bool) setthreadpriority:(double) p;

Set the name of the thread

-(void) setname:(nsstring *) n;
</p>
<p>
-(nsstring *) name;

Other ways to create threads

(2) Automatically start the thread after it is created [nsthread detachnewthreadselector:@selector (run) totarget:self withobject:nil];

(3) implicitly create and start the thread [self performselectorinbackground:@selector (run) withobject:nil];

Advantages and disadvantages of the above two ways to create threads

Pros:Simple and fast

Disadvantage:Unable to set threads in more detail

Fourth, multi-threaded code examples

1. Create in an ancient way

//
//yyviewcontroller.m
//
//
//created by apple on 14-6-23.
//copyright (c) 2014 itcase. all rights reserved.
//
</p>
<p>
#import "yyviewcontroller.h"
#import<pthread.h>
</p>
<p>
@interface yyviewcontroller ()
-(ibaction) btnclick;
@end
</p>
<p>
@implementation yyviewcontroller
</p>
<p>
-(void) viewdidload
{
 [super viewdidload];
}
</p>
<p>
//button click event
-(ibaction) btnclick {
 //1. Get the current thread
 nsthread * current=[nsthread currentthread];
 //Main thread
 nslog (@ "btnclick ----%@", current);
</p>
<p>
//2. Use a for loop to perform some time-consuming operations
 pthread_t thread;
 pthread_create (&thread, null, run, null);
}
</p>
<p>
//c language function
void * run (void * data)
{
 //Get the current thread,Is a newly created thread
 nsthread * current=[nsthread currentthread];
</p>
<p>
 for (int i=0;i<10000;i ++) {
 nslog (@ "btnclick ---%d ---%@", i, current);
 }
 return null;
}
</p>
<p>
//multiple threads,When you click the button to execute the button call method,The main thread is not blocked
</p>
<p>
@end

Realize the effect:

Print results:

2. Create a thread using nsthread

//
//yyviewcontroller.m
//
//
//created by apple on 14-6-23.
//copyright (c) 2014 itcase. all rights reserved.
//
</p>
<p>
#import "yyviewcontroller.h"
#import<pthread.h>
</p>
<p>
@interface yyviewcontroller ()
-(ibaction) btnclick;
@end

@implementation yyviewcontroller
</p>
<p>
-(void) viewdidload
{
 [super viewdidload];
}
</p>
<p>
//button click event
-(ibaction) btnclick {
 //1. Get the current thread
 nsthread * current=[nsthread currentthread];
 //Main thread
 nslog (@ "btnclick ----%@", current);
</p>
<p>
//Another way to get the main thread
 nsthread * main=[nsthread mainthread];
 nslog (@ "the Lord Thread -------%@", main);
</p>
<p>
//2. Perform some time-consuming operations
 [self creatnsthread];
//[self creatnsthread2];
//[self creatnsthread3];
}
</p>
<p>
/**
* nsthread create thread mode 1
* 1>Create the initialization thread first
* 2>start thread
* /
-(void) creatnsthread
{
 nsthread * thread=[[nsthread alloc] initwithtarget:self selector:@selector (run :) object:@"Threada"];
 //Set a name for the thread
 thread.name [email protected]"Threada";
 //Start the thread
 [thread start];
</p>
<p>
nsthread * thread2=[[nsthread alloc] initwithtarget:self selector:@selector (run :) object:@"Threadb"];
 //Set a name for the thread
 thread2.name [email protected]"Threadb";
 //Start the thread
 [thread2 start];
}
</p>
<p>
/**
* nsthread create thread mode 2
* Directly (automatically) start after creating a thread
* /
</p>
<p>
-(void) creatnsthread2
{
//nsthread * thread=[nsthread detachnewthreadselector:@selector (run :) totarget:self withobject:@"start (automatically) start the thread"];
</p>
<p>
[nsthread detachnewthreadselector:@selector (run :) totarget:self withobject:@"Directly (automatically) started after creating a thread"];
}
</p>
<p>
/**
* nsthread create thread mode 3
* Implicitly create threads, And start directly (automatically)
* /
</p>
<p>
-(void) creatnsthread3
{
 //Execute in background thread === Execute in child thread
 [self performselectorinbackground:@selector (run :) withobject:@"Implicitly created"];
}
</p>
<p>
-(void) run:(nsstring *) str
{
 //Get the current thread
 nsthread * current=[nsthread currentthread];
 //print output
 for (int i=0;i<10;i ++) {
 nslog (@ "run ---%@---%@", current, str);
 }
}
@end

Call thread 1, and print the result:

Calling thread 2

Calling thread 3

ios
  • Previous Analysis of the difference between C ++ front and back
  • Next Summary of ASPNET Programming to Get the Website Root Directory