IOS Multi-Threading 01

Source: Internet
Author: User

    • Process

      • A process is an application that is running in the system
    • Thread

      • 1 processes to perform a task, a thread must be wired (at least 1 threads per 1 processes)
      • The execution of a task in 1 threads is serial ( 执行完上一个才能执行下一个 )
    • Multithreading

      • Multiple threads can be opened in 1 processes, multiple threads can perform different tasks in parallel (at the same time)
      • Threads can be parallel, but the tasks in each thread are still serial
    • Multithreading principle

      • Multi-threaded concurrency (simultaneous) execution, in fact, the CPU is quickly dispatched between multiple threads (switching)
    • Multithreading pros and cons

      • Advantages
        • To improve the execution efficiency of the program appropriately
        • Can appropriately improve resource utilization (CPU, memory utilization)
      • Disadvantages
        • The more threads, the greater the overhead of the CPU on the dispatch thread
        • If a large number of threads are turned on, the performance of the program is reduced
        • 程序设计更加复杂:比如线程之间的通信、多线程的数据共享
  • Pthread
    • Type: The end of a type in C is usually _t/ref and does not need to be used *
    • /*parameters: 1. Thread code address 2. Thread's properties 3. Pointer to the function called-void * (*) (void *)-return value (function pointer) (parameter)-void * and ID in OC is equivalent to 4. The return value of the parameter passed to the function: if 0, the table If it is non-0, the error code is indicated*/NSString*str =@"JX";p thread_t thid;intres = Pthread_create (&thid, NULL, &demo, (__bridgevoid*) (str));if(res = =0) {NSLog (@"OK");} Else{NSLog (@"Error%d", res);}
  • Nsthread

    • A Nsthread object represents a thread
  • Several ways to create threads

  •  //  1. Create thread  njthread *thread = [[ Njthread Alloc] initwithtarget:self selector: @selector (Demo:) object : @ "  JX   ";  //  set the thread name [thread setname:@ "LJX"];  //  //   [Thread Setthreadpriority:1.0   //  2. Start thread [thread start]; 
    -detach/performselector    + Pros: Simple and    fast + Cons: Unable to set the thread in more detail ' OBJC//  1. Create Thread [nsthread detachnewthreadselector: @selector (Demo:) totarget:self withobject:@ "jx" ]; // 1. Create a thread // Note: Not available in Swift, Apple considers this method    unsafe [Self Performselectorinbackground: @selector (Demo:) Withobject:@ "jx"];
  • Thread state
  • Start thread Nsthread*thread = [[Nsthread alloc] initwithtarget:self selector: @selector (Run)Object: nil];    [Thread start]; //go to Ready status, run status. Automatically enters the death state when the thread task is completedblocking (pausing) threads+ (void) Sleepuntildate: (NSDate *) Date; + (void) Sleepfortimeinterval: (Nstimeinterval) ti; //Enter blocking StateForce Stop Thread+ (void) exit; //into the state of deathNote: Once the thread has stopped (dead), it cannot be opened again.

    The security hidden trouble of multithreading

      • Locked code can only be executed by one thread at a time
      • // code that needs to be locked  }
  • Advantages and disadvantages of mutual exclusion lock: can effectively prevent the data security problem caused by multi-thread snatch resources disadvantage: the need to consume a lot of CPU resources

  • Mutual exclusion Lock attention point

    • Lock 1 copies of code with only 1 locks, with multiple locks is not valid
    • The larger the locking range, the worse the performance
  • Atomic and non-atomic properties

    • Atomic: Thread-safe, requires a lot of resources
    • Nonatomic: Non-thread-safe, suitable for small memory mobile devices
  • Spin Lock & Mutual Exclusion lock

    • Common denominator ensures that only one thread executes a locked range of code at the same time
    • Different points
      • Mutex: If another thread is found to be executing the locked code, the thread goes into a "hibernate" state, waits for the other thread to finish, and after the lock is opened, the thread is "awakened"
      • Spin lock: If another thread is found to be executing the locked code, the thread will "wait" for the lock code to finish executing! Spin lock is more suitable for executing very short code!
  • Inter-thread communication
      • Child threads do time-consuming operations, the main thread updates the data
  • #import "ViewController.h"@interfaceViewcontroller () @property (weak, nonatomic) Iboutlet Uiimageview*ImageView;@end@implementationViewcontroller- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{        //Open a sub-thread download picture[Self performselectorinbackground: @selector (Downlod) withobject:nil];}- (void) downlod{NSLog (@"%@", [Nsthread CurrentThread]); //1. Download the imageNsurl *url = [Nsurl urlwithstring:@"http://pic.4j4j.cn/upload/pic/20130531/07ed5ea485.jpg"]; NSData*data =[NSData Datawithcontentsofurl:url]; //2. Convert binary to PictureUIImage *image =[UIImage Imagewithdata:data]; //3. With the new UI#warningNote: Never update the UI in a child thread, there will be problems/*Waituntildone:yes: If you pass in YES, you will wait for the UpdateImage method to finish before continuing with the following code no: If you pass in no, you will not wait for the UpdateImage method to finish, You can continue after the following code*/    /*[Self performselectoronmainthread: @selector (updateimage:) withobject:image Waituntildone:no]; */        //Common in development//[Self.imageview performselectoronmainthread: @selector (setimage:) withobject:image Waituntildone:yes]; //you can invoke the specified method of the specified object in the specified thread[Self performselector: @selector (updateimage:) onthread:[nsthread Mainthread] Withobject:image waituntildone:yes    ]; }- (void) UpdateImage: (UIImage *) image{NSLog (@"%@", [Nsthread CurrentThread]); //3. Updating the UISelf.imageView.image =image; }
  • GCD
  • There are 2 core concepts in GCD

    • Task: what action to take
    • Queues: Used to store tasks
  • Perform tasks

    • Synchronization method: Dispatch_sync
    • Async method: Dispatch_async
    • The difference between synchronous and asynchronous
      • Synchronization: Tasks can only be performed in the current thread, without the ability to open new threads
      • Async: Can perform tasks in a new thread, with the ability to open new threads
  • Queue

    • Concurrent queues
      • Multiple tasks can be executed concurrently (concurrently) (automatic opening of multiple threads concurrently executing tasks)
      • concurrency function is only valid under asynchronous (Dispatch_async) functions
      • The gcd default already provides a global concurrency queue for the entire application to use, eliminating the need to manually create a global concurrency queue dispatch_queue_t using the Dispatch_get_global_queue function Dispa Tch_get_global_queue (dispatch_queue_priority_t priority,//priority of the queueUnsignedLongFlags);//This parameter is temporarily useless and can be used with 0Obtaining global concurrent queues dispatch_queue_t queue= Dispatch_get_global_queue (Dispatch_queue_priority_default,0); Priority of global concurrent queues#defineDispatch_queue_priority_high 2//High            #defineDispatch_queue_priority_default 0//Default (Medium)            #defineDispatch_queue_priority_low (-2)//Low            #defineDispatch_queue_priority_background Int16_min//Backstage

    • 串行队列    * 让任务一个接着一个地执行(一个任务执行完毕后,再执行下一个任务)
    •         2 ways to get serial in GCD        use the Dispatch_queue_create function to create a        serial queue //  Create a serial queue (queue type passed null or dispatch _queue_serial)        dispatch_queue_t QUEUE = dispatch_queue_create ("com.520it.queue " , NULL);        Using the primary queue (the queue associated with the main line threads) the Home        column is the task that the GCD comes with a special serial queue        placed in the main queue, which is put into the main thread to execute        using Dispatch_get_main_queue () to get the host column         = Dispatch_get_main_queue ();
    • Watch out.

      Primary impact of synchronous and asynchronous: Can I open a new thread
      • Synchronous: Only performs tasks in the current thread, does not have the ability to open new threads
      • Async: Can perform tasks in a new thread, with the ability to open new threads
      Concurrency and serial primary impact: How tasks are executed
      • Concurrency: Allows multiple tasks to execute concurrently (concurrently)
      • Serial: Once a task is completed, the next task is performed
    • Various task Queue collocation

      • Sync + serial *
      • Sync + concurrency *
      • Asynchronous + serial *
      • Asynchronous + concurrency *
      • Async + Home Row *
      • Sync + Home Row *
    • GCD Inter-thread communication

    • 0), ^{    //  Execute time-consuming asynchronous operation      ... Dispatch_async (Dispatch_get_main_queue (), ^{        ///  return to main thread, perform UI refresh Operation         }) ;
    • GCD Other uses
    • Delay execution
    • Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{    ///  2 seconds after executing the code here...});

    • Disposable code

      • Use the Dispatch_once function to ensure that a piece of code 程序运行过程中 is executed only 1 times
    • Static // execute code only 1 times (which is thread-safe by default)});

    • 快速迭代
    • Dispatch_apply (dispatch_get_global_queue (00), ^(size_t index) {       Execute 10 times Code, Index order indeterminate });
    • Barrier
      • It does not execute until after the execution of the previous task, and the task after it is completed before it executes
      • 不能是全局的并发队列
      • 所有的任务都必须在一个队列中
      • Dispatch_barrier_async (dispatch_queue_t queue, dispatch_block_t block);
    • Queue Group
    • dispatch_group_t Group =  0), ^{    //  Execute 1 time-consuming asynchronous operations  0 ), ^{    //  Execute 1 time-consuming asynchronous operations  ^{    //  When the previous asynchronous operation is complete, return to the main thread ...});
    • Multi-threading implementations in iOS

    • Single-Case mode

      • The role of the singleton pattern

        - 可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源
      • The use of single-case mode

        • Share a single resource throughout the application (this resource only needs to be initialized 1 times)
      • In Arc, the implementation of the singleton mode

      • keep An instance of global static in. MStatic ID_instance; Override Allocwithzone: Method, create a unique instance here (Note thread safety)+ (Instancetype) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken,^{_instance=[Super Allocwithzone:zone];             }); return_instance; Provides 1 class methods for accessing unique instances from outside+(instancetype) sharedinstance {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Self alloc] init];            }); return_instance; } Implement Copywithzone: Method- (ID) Copywithzone: (struct_nszone *) Zone {return_instance; Pay attention.//Note: A singleton is not inheritable if inheritance raises a problem//If you first create a parent class, it will always be the parent class//If you create a subclass first, it's always a subclass

IOS Multi-Threading 01

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.