iOS Multithreading technology---pthread, nsthread, Nsoperationqueue, GCD

Source: Internet
Author: User

Multithreading Technology

Process: An application running in the system; each process is independent; there is a proprietary memory space

Thread threads: A sequence of execution of a program, not part of a process;

Features: 1. The process allocates only memory space and does not perform tasks

2. Each process has at least one thread, which is called the main thread

3, the thread is the basic execution unit of the process, all the tasks of the process are executed in the thread

4, each thread in the execution of the task is serial

Multithreading Concurrency: Multiple threads in a process execute tasks concurrently;

Features: 1, improve the execution efficiency of the program, improve resource utilization

2, at the same time, the CPU can only process one thread

3, multi-threaded concurrency, the CPU in multiple threads quickly switch between

4, thread switching speed quickly, resulting in multi-threaded concurrent execution

5, the open thread needs memory space, too many threads will cause the schedule to consume too many resources

6. Too many threads will reduce the frequency of each thread being dispatched (thread execution efficiency is reduced)

Multi-threaded applications:

Main thread: Display refresh UI, handle UI events, time consuming tasks (such as downloads) placed in child threads

The decision method is executed in which thread: NSLog (@ "Current thread:", [Nsthread CurrentThread]);

Four kinds of multithreading technology: Pthread Nsthread

pthread

C-based API, can write multi-platform applications, difficult to use, you need to manually create the destruction of the thread, can be customized less functionality

pthread_t pthread;

void *task (void *data) {

NSLog (@ "Current sub-thread:%@", Nsthread CurrentThread];

return 0;

}

Pthread_create (&pthread,null,task,null);

Nsthread

Based on OC, easy to use relative to pthread, object oriented

Cons: Need to manage thread lifecycle, thread synchronization, locking, unlocking, managing multiple threads is more difficult

Three ways to manually create threads:

1, nsthread instance method:-(Instancetype) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) Argument ns_available ( 10_5, 2_0); ( create only )

2, Nsthread class method: + (void) Detachnewthreadselector: (SEL) selector totarget: (ID) target withobject: (id) argument; ( Create and run )

3. Nsthread instance method:-(void) Performselectorinbackground: (SEL) Aselector withobject: (ID) arg ns_available (10_5, 2_0);

Note: selector: Thread execution method, this selector can only be by one parameter, and there is no return value

Object: The only parameter passed to target, or nil

Target:selector messages Send only the first one to set the name, priority

Thread Blocking:

Sleep law?: Start sleeping for 5 seconds

[Nsthread Sleepfortimeinterval:5];

Sleep Law II:

NSDate *date = [NSDate datewithtimeintervalsincenow:3

[Nsthread Sleepuntildate:date];

Force Stop Thread:

[Nsthread exit];

Other common methods:

+ (Nsthread *) Mainthread; Get the main thread

-(BOOL) ismainthread;//determine if the main thread

+ (double) threadpriority;//get thread Priority priority value range 0.0~1.0 value higher priority

+ (BOOL) SetThreadPriority: (double) p;//set priority

-(nsstring*) name;//get thread name

-(void) SetName: (nsstring*) n;//set thread name

The state of the thread:

New (new), Runnable (Ready)--the CPU starts dispatching the current thread---> Running (run)---> Call the Sleep method---> Blocked (blocking)---> Remove the thread pool--- > Sleep Execution Complete/---> ENTER thread pool---> Runnable (Ready)

If the thread task finishes/exception/force exits---> Dead (Death)

Locking

Try to avoid using @synchronized, which is to avoid multiple threads accessing the same resource, because locking, unlocking requires a larger CPU resource

Lock-In: When multiple threads access the same resource at the same time, they need to lock (mutex)

Thread synchronization: Multiple threads executing on the same line (performing tasks sequentially)

Try to speak locking, resource-grabbing business logic delivery server-side processing, reducing the pressure on mobile clients

Synchronized keywords

1, the scope of the SYNCHRONIZED keyword has two kinds:

1) is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, As long as a thread accesses one of the synchronized methods, the other thread cannot access any of the synchronized methods in the object at the same time. At this point, the synchronized method of the different object instances is not interfering. In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;

2) is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class.

2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access. The usage is: synchronized (this) {}, which is scoped to the current object;

Atomic and non-atomic properties:

Nonatomic: non-atomic, not locked in the set method, this is the recommended way, will consume less resources

Atomic: Atomic---lock in the set method to prevent multiple threads from executing the Set method at the same time

Inter-thread communication:

1. In a process, threads often do not exist in isolation and require frequent communication between multiple threads

2. How to communicate between threads:

One thread passes data to another thread

After performing a specific task in one thread, go to another thread to continue the task

iOS Multithreading technology---pthread, nsthread, Nsoperationqueue, GCD

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.