iOS Development Multithreading Basics

Source: Internet
Author: User

--------------------------Multithreaded Conceptual Foundation-------process: Running program Memory: the storage space thread that each process occupies: a process to perform a task, a thread that must be wired, a process's basic execution unit, a thread's serial: • The execution of the characters in 1 threads is serial • 0 in the same time, 1 threads can perform only one task 0 • Threads are an execution path for a process--------multithreading • Multiple threads can be opened in a process, each thread can parallel (simultaneously) perform different tasks • Process-"Shop thread-" Workshop worker thread parallelism: • Simultaneous execution of multiple threads in the process can improve the execution efficiency of the program---multi-threading principle • At the same time, the CPU can only process one thread, only 1 threads are working (executing) • Multithreading concurrency (simultaneous) execution, in fact, the CPU fast between multiple threads (switching) · If the CPU schedules the thread fast enough, it creates the illusion of multi-threaded concurrency and thinking: There are so many threads, what happens: CPU draws n multi-threaded scheduling, CPU is exhausted, consumes a lot of CPU resources The frequency at which each thread is scheduled to execute is reduced (the execution of the thread is less efficient)---the pros and cons of multithreading-The advantages of Multithreading: • 1. Can be sprints improve the execution efficiency of the program • 2. Can appropriately improve resource utilization (CPU, memory utilization)-The disadvantage of Multithreading: • 1. Open threads need to occupy a certain amount of memory space, if you open a large number of fields, will take up a lot of memory space, reduce program performance • 2. The more threads, the more the CPU spends on scheduling thread deletions. • 3. Programming is more complex: for example, communication between threads, Multi-threaded data sharing-------------------------the application of multithreading in iOS development--------• I. Main thread 1. After an iOS program runs, 1 threads are turned on by default, called "Main thread" or "UI thread" 2. Main role of Main thread • Display, refresh UI interface • Handle UI events (click, scroll, drag) 3. Main thread usage Note: • Do not put more time-consuming operations on the mainline approached (affect UI fluency) • If the time-consuming operation is placed in the main thread, the main thread is serial execution, the user will feel very card, the user experience will be very poor two. Execution of time-consuming operations 1. Place time-consuming operations on sub-threads (rear antenna path, non-main thread) • Benefits: ① reacts at the moment the user taps the button; ② can simultaneously handle event three for time-consuming operations and UI controls. Multi-Threading implementation in iOS 1.pthread:c language ① a unified set of multi-threaded Api② used with UNIX, Linux, Windows and other systems ③ cross-platform, Portable ④ is more difficult to use than ⑤. The programmer manages the thread declaration cycle ⑥. Usage frequency: Almost no 2.nsthread:oc language ① using more object-oriented ② is simple and easy to use,You can manipulate thread object ③ directly. Thread Declaration cycle: Programmer Management ④. Occasional use of 3. Gcd:c language ① pointers replace Nsthread and other threading techniques ② reusing devices for multicore ③. Thread life cycle: Automatic Management ④ Usage frequency: use 4 frequently. The Nsoperation OC language ① is based on GCD (the underlying is GCD) ② has some more determined features GCD than ③ using more object-oriented ③. Thread life cycle: Automatic Management ④ Usage frequency: Use-------to create and start thread--1 frequently. A Nsthread object represents a thread 2. Create, start thread nsthread *thread = [[Nsthread alloc] Initwithtarget:self selector (run) Object:nil]; [Thread start];//thread starts, it executes self's Run Method 3. Main thread correlation usage + (Nsthread *) Mainthread; Get the main thread-(BOOL) Ismainthread; is the main thread + (BOOL) Ismainthread; is the main thread-----other usage--1. Get current thread Nsthread *current = [nsthread currentthread];2. Scheduling Priority of Threads + (double) threadpriority;+ (BOOL) SetThreadPriority: (Double) p;-(double) threadpriority;-(BOOL) SetThreadPriority: (double) p; The value range of the dispatch priority is 0.0 ~  1.0, default 0.5, the greater the value, the higher the Priority 3. Thread name-(void) SetName: (NSString *) n;-(NSString *) name;-------3 ways to create threads----/** * Nsthread creation mode 3: Implicit thread creation, and direct (auto) start thread */-(void) threadcreate3{[self performselectorinbackground: @selector (run:) withobject:@ "333333"];} /** * Create Mode 2: Automatically start thread */-(void) threadcreate2{//detached sub-thread after creating thread [Nsthread detachnewthreadselectOr: @selector (run:) totarget:self withobject:@ "2222222"];} /** * Creation Method 1:① first creates the initialization child thread ② restart */-(void) threadcreate{nsthread *thread1 = [[Nsthread alloc] initwithtarget:self selector:    @selector (run:) object:@ "Heheh"];    Thread1.name = @ "Thread1";        Open thread [thread1 start];    Nsthread *thread2 = [[Nsthread alloc] initwithtarget:self selector: @selector (run:) object:@ "Heheh"];    Thread2.name = @ "Thread2";        Open thread [thread2 start];    Nsthread *thread3 = [[Nsthread alloc] initwithtarget:self selector: @selector (run:) object:@ "Heheh"];    Thread3.name = @ "33"; Open thread [thread3 start];} ----~ Method 2,3 Advantages and disadvantages relative to Method 1 • Advantages: simple and fast • OK: Unable to set the thread in more detail-----------------The 5 states of the thread--------new ready run blocking death nsthread *thread1 = [[ Nsthread Alloc] initwithtarget:self selector: @selector (run:) object:@ "Heheh"]; The code finishes executing, creates a new thread object in memory, does not run in the new state, and then calls [ Thread1 start]; A scheduled thread pool will appear in memory, after the start state, the new thread from the new state to the ready state, waiting for the CPU scheduling, once the CPU is dispatched, it will change from the ready state to the running state, if the CPU dispatches other thread objects, The thread object becomes ready again, and then it is dispatched to the running state. If you call the Sleep method and wait for a synchronous lock, the thread object will first go into a blocking state and it willA scheduled thread pool clears the thread task execution, exception, force exit, thread objects into the dead state, thread objects are also removed from the thread dispatch pool, but still in memory. -----------Control thread State------1. Start thread-(void) start;//into ready state-"running state." When the pickle task is completed, it automatically enters the death State 2. Blocking (pausing) thread + (void) Sleepuntildate: (NSDate *) date;+ (void) Sleepfortimeinterval: (Nstimeinterval) Ti ;//Enter the blocking State 3. Force stop thread + (void) exit;//Enter the death state, note: Once in the state of death, the thread can no longer use//notice: Once the thread Tingzhil, No, brother. This opens the Task--------------thread security (multi-threaded security implications)-------1. Resource Sharing • A resource may be shared by multiple threads, i.e. multiple threads may access the same piece of resources • For example, multiple threads access the same object, the same variable, Same file 2. When multiple threads access the same piece of resources, data confusion and data security issues can easily be raised 3. Instance eg. 1 save money to take out eg. 2 Selling Tickets-----------------security hazard resolution-Mutex-----1. Format @synchronized (lock object) {//code to be locked} NOTE: Locking a copy of the code can only be used with 1 locks, with multiple locks is not valid for 2. Advantages and Disadvantages · Advantages: Can effectively prevent multi-threaded snatch resources caused by security problems • Cons: Requires a lot of CPU resources 3. Mutex use premise: multiple threads rob the same piece of resources 4. Related terms: Thread synchronization means: Multiple threads perform tasks sequentially Mutex is the use of thread synchronization technology-----------------Atomic and non-atomic properties----------------------1. OC has nonatomomic and atomic two choices when defining attributes Atomic: Atomic properties, locking for setter methods (atomic by default) Nonatomic: Non-atomic attribute, no lock 2.atomic lock principle for setter method @    Property (assign, atomic) int age;-(void) Setage: (int.) age{@synchronized (self) {_age = age; }}----------the selection of atomic and non-atomic properties----1.nonatomic and atomic contrast ·Atomic: Thread-safe, requires a lot of resources nonatomic: Non-thread-safe, suitable for small memory mobile devices 2.iOS Development recommendations • All properties are declared as Nonatomic try to avoid multithreading to rob the same piece of resources • Try to locking, Resource-grabbing business logic is given to server-side processing, reducing the pressure on mobile clients-----------------communication between Threads----------------------1. What's called Inter-threading Communication • In a process, threads tend not to encourage frustration, Communication between multiple threads 2. The embodiment of inter-thread communication • One thread passes data to another thread • After a specific task is executed in one thread, go to another thread to continue to perform task 3. Common methods for inter-thread communication-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait;-(void) Performselector: ( SEL) Aselector onthread: (Nsthread *) THR Withobject: (ID) arg waituntildone: (BOOL) wait;---------------- GCD---------------1. GCD Full Name: Grand Central Dispatch, translated as "great Hub Scheduler", pure C language, provides the fly-away powerful function 2. Advantages of GCD · GCD is Apple's solution for multi-core parallel operations · GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core) · GCD automatically manages the lifecycle of threads (creating threads, scheduling tasks, destroying threads) • Programmers need to tell gcd what tasks they want to perform without writing any thread-management code------GCD tasks and Queues--1.GCD 2 core concepts: • Task: What to do · Queue: Used to hold Task 2. GCD is used in 2 steps ① Customizing tasks: • Determine what you want to do ② add a task to the queue: • GCD automatically takes the task out of the queue and places it in the corresponding thread execution • "The task's removal follows the queue FIFO principle: First Post-----GCD perform tasks-----1.GCD has 2 functions to perform tasks • Perform tasks in a synchronous manner Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block) · Queue: Queues • Block: Tasks • Perform tasks asynchronously (Dispatch_async)dispatch_queue_t queue, dispatch_block_t block); 2. Synchronization and Asynchronous differences • Synchronization: Executing in the current thread · Async: A queue type that executes-------GCD in another thread----a queue of 1.GCD can be divided into two types • Concurrent Queue (Concurrent Dispatch queue) to allow multiple tasks to execute concurrently (simultaneously) (automatically open multiple threads simultaneously) Concurrency is only valid in asynchronous functions (Dispatch_async) • Serial queue (Serial dispatch queue) lets the task execute one after another (after a task is executed, In the next task)---------confusing terminology in GCD----1. There are four terms that are easier to confuse: synchronous, asynchronous, concurrent, serial, synchronous, and asynchronous determine whether to start a new thread • Synchronize: Perform a task in the current thread without the ability to open a new thread · Async: Perform a task in a new thread with the ability to open a new thread • Concurrency and serial determine how tasks are executed • Concurrent: Multiple tasks concurrent (simultaneous) execution • Serial: Once a task is executed, Perform the next task---the concurrent queue for GCD---1.GCD has already provided a global concurrent queue for the entire application to use, without the need for manual creation • Use the Dispatch_get_global_queue function to obtain a global concurrency queue Dispatch_queue _t Dispatch_get_global_queue (dispatch_queue_priority_t priority,//queue precedence Unsign Ed long flags; This parameter is temporarily useless, 0 can be used);d ispatch_queue_t queue = dispatch_get_global_queue (Dispatch_queue_priority_default, 0); Get global concurrency Queue 2. Priority of global concurrent queue • #define DISPATCH_QUEUE_PRIORITY_HIGH 2//High • #define DISPATCH_QUEUE_PRIORITY_DEFAULT 0//default (Medium) · #define Dispatch_queue_priority_low (-2)//low • #define Dispatch_queue_priority_backgrouND int16_min//Background----GCD serial queue----1.GCD 2 ways to obtain serial dispatch_queue_create • Ungjchuanx queue Dispatch_queue_tdispatch_ Queue_create (const char *label,//queue name dispatch_queue_attr_t attr//queue property, generally null);d ispatch_queue_t queue = Dispatch_ Queue_create ("Cn.itcast.queue", NULL); Create dispatch_release (queue); Non-arc needs to be sensational release queue created • Use the primary queue (the queue associated with the mainline threads) • The home row is a special serial queue that GCD comes with. • Tasks placed in the main queue are placed in the primary thread execute • "Use Dispatch_get_main_queue () Get the home row dispatch_queue_t queue = Dispatch_get_main_queue (),-----gcd The execution effect of various queues----/** * Use dispatch_async async functions,    Add Task */-(void) Testasyncmainqueue {//1. Get the home queue dispatch_queue_t queue = Dispatch_get_main_queue () in the main thread    2. Add task to queue, perform task Dispatch_async (queue, ^{NSLog (@ "---------1-----%@", [Nsthread CurrentThread]);        }); Summary: Do not open the new thread}/** * Use the Dispatch_sync synchronization function, the main thread in the master queue to add tasks, dead: The task cannot be executed down */-(void) Testsyncmainqueue {//1. Get the home row Dispat    ch_queue_t queue = Dispatch_get_main_queue (); 2. Add task to queue, perform task Dispatch_sync (queue, ^{NSLog (@ "---------1-----%@ ", [Nsthread CurrentThread]);            }); Summary: Do not open a new thread, all tasks in the main thread serial execution}//all function names with Create, copy, new, retain and other words, you need to use this data when you do not need to release// GCD data types do not need to do release//CF (Core Foundation) data type in ARC environment still do release-(void) testcf {cfarrayref array = Cfarraycre    ATE (null, NULL, one-by-one, null); Cfrelease (array);} /** * Add a task to the serial queue with the Dispatch_sync sync function */-(void) Testsyncserialqueue {//1. Creating a serial queue dispatch_queue_t queue = Dispatch_qu        Eue_create ("Cn.dongyue.queue", NULL);    2. Add task to queue, perform task Dispatch_sync (queue, ^{NSLog (@ "---------1-----%@", [Nsthread CurrentThread]);    });    Dispatch_sync (Queue, ^{NSLog (@ "---------2-----%@", [Nsthread CurrentThread]);    });    Dispatch_sync (Queue, ^{NSLog (@ "---------3-----%@", [Nsthread CurrentThread]);        });            3. Release (MRC)//dispatch_release (queue); Summary: Do not open a new thread}/** * Add a task to the concurrent queue with the Dispatch_sync synchronization function */-(void) Testsyncglobalqueue {//1. Get global concurrency queue dispatch_queue_t qu Eue = Dispatch_get_global_queue(Dispatch_queue_priority_default, 0);    2. Add task to queue, perform task Dispatch_sync (queue, ^{NSLog (@ "---------1-----%@", [Nsthread CurrentThread]);    });    Dispatch_sync (Queue, ^{NSLog (@ "---------2-----%@", [Nsthread CurrentThread]);    });    Dispatch_sync (Queue, ^{NSLog (@ "---------3-----%@", [Nsthread CurrentThread]);        }); Summary: New threads are not opened and concurrent queues lose concurrency}/** * Add tasks to the concurrent queue with the Dispatch_async synchronization function */-(void) Testasyncserialqueue {//1. Creating a serial queue DISPATC        h_queue_t queue = dispatch_queue_create ("Cn.dongyue.queue", NULL);    2. Add task to queue, perform task Dispatch_async (queue, ^{NSLog (@ "---------1-----%@", [Nsthread CurrentThread]);    });    Dispatch_async (Queue, ^{NSLog (@ "---------2-----%@", [Nsthread CurrentThread]);    });    Dispatch_async (Queue, ^{NSLog (@ "---------3-----%@", [Nsthread CurrentThread]);        }); Summary: Open only 1 new threads, do not open new thread}/** * Add task to concurrent queue with Dispatch_async sync function */-(void) Testasyncglobalqueue {//1. Get Global concurrency Queue DISPATC H_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);    2. Add task to queue, perform task Dispatch_async (queue, ^{NSLog (@ "---------1-----%@", [Nsthread CurrentThread]);    });    Dispatch_async (Queue, ^{NSLog (@ "---------2-----%@", [Nsthread CurrentThread]);    });    Dispatch_async (Queue, ^{NSLog (@ "---------3-----%@", [Nsthread CurrentThread]);    }); Summary: Open 3 threads at the same time----------example of inter-thread communication---------1. From the child thread back to the main thread (download picture)-(void) Testbacktomain {//Get global concurrent queue dispatch_queue_t que    UE = Dispatch_get_global_queue (dispatch_queue_priority_default, 0);        Asynchronous queue Dispatch_async (queue, ^{NSLog (@ "-----%@", [Nsthread CurrentThread]);        Download image NSString *path = @ "URL of image link";        Nsurl *url = [Nsurl Urlwithstring:path];                NSData *data = [NSData Datawithcontentsofurl:url];        UIImage *image = [UIImage imagewithdata:data]; Back to main thread display picture Dispatch_async (Dispatch_get_main_queue (), ^{NSLog (@ "-----------%@", [Nsthread CurrentThread]);        Self.iconView.image = image;    }); });} --------gcd delay Execution----1.iOS common delay execution in 2 ways • Call NSObject method [self performselector: @selector (run) Withobject:nil Afterdelay : 2.0];//call Self's Run method after 2 seconds • Use GCD function-(void) Testdelay {dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (5.0 *    NSEC_PER_SEC)), Dispatch_get_main_queue (), ^{NSLog (@ "222"); });}    ---------Disposable Code------(void) testonce {static dispatch_once_t oncetoken;    Dispatch_once (&oncetoken, ^{NSLog (@ "once"); });} ------------Queue Group------1. There is a need. • First: Perform 2 time-consuming operations asynchronously separately • Second: 2 Each asynchronous operation is completed, then return to the main thread to perform Operation 2. If you want to implement these requirements quickly and efficiently, consider using queue groups-(void)    Touchesbegan: (Nsset *) touches withevent: (uievent *) event{NSLog (@ "%@", [Nsthread CurrentThread]);    dispatch_group_t group = Dispatch_group_create ();        dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);    __block UIImage *icon1 = nil; Dispatch_group_async (group, queue, ^{NSLog (@ "%@", [Nsthread curRentthread]);            Icon1 = [Self imagewithurl:@ "http://image.cache.xiu8.com/live/125/125/997729.jpg"];    });    __block UIImage *icon2 = nil;        Dispatch_group_async (group, queue, ^{NSLog (@ "%@", [Nsthread CurrentThread]); Icon2 = [Self imagewithurl:@] Http://news.baidu.com/z/resource/r/image/2014-06-22/b2a9cfc88b7a56cfa59b8d09208fa1    Fb.jpg "];        });        Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{NSLog (@ "%@", [Nsthread CurrentThread]);        Self.iconV1.image = Icon1;                Self.iconV2.image = Icon2;        Uigraphicsbeginimagecontextwithoptions (Cgsizemake (max.), NO, 0);        [Icon1 drawinrect:cgrectmake (0, 0, 100, 100)];        [Icon2 drawinrect:cgrectmake (100, 0, 100, 100)];                Self.bigIconV.image = Uigraphicsgetimagefromcurrentimagecontext ();    Uigraphicsendimagecontext (); });}    -(UIImage *) Imagewithurl: (NSString *) iconpath{NSLog (@ "%@", [Nsthread CurrentThread]);Nsurl *url = [Nsurl Urlwithstring:iconpath];    NSData *data = [NSData Datawithcontentsofurl:url]; return [UIImage Imagewithdata:data];}

 

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.