IOS multithreading 01 and ios multithreading 01

Source: Internet
Author: User

IOS multithreading 01 and ios multithreading 01

  • Process

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

    • To execute a task, one process must have at least one thread (each process must have at least one thread)
    • Task execution in one thread is serialized (The next task can be executed only after the previous task is executed.)
  • Multithreading

    • Multiple Threads can be enabled in one process, and multiple threads can execute different tasks in parallel (at the same time ).
    • Threads can be parallel, but tasks in each thread are serialized.
  • Multithreading Principle

    • Multi-thread concurrent (concurrent) execution is actually a fast CPU scheduling (switching) between multiple threads)
  • Advantages and disadvantages of Multithreading

    • Advantages
      • Appropriately improves program execution efficiency
      • Resource utilization can be appropriately improved (CPU and memory usage)
    • Disadvantages
      • The more threads, the higher the CPU overhead on the scheduling thread.
      • Enabling a large number of threads will reduce program performance.
      • Program Design is more complex: for example, communication between threads and multi-thread data sharing
  • Pthread
    • Type: The end of the type in C is usually _ t/Ref, and you do not need to use *
    • /* Parameter: 1. thread Code address 2. thread attributes 3. call the function pointer-void * (*) (void *)-return value (function pointer) (parameter)-void * is equivalent to the id in OC 4. return Value of the parameter passed to this function: If it is 0, it indicates that the value is correct. If it is not 0, it indicates the error code */NSString * str = @ "jx"; pthread_t thid; int res = pthread_create (& thid, NULL, & demo, (_ bridge void *) (str); if (res = 0) {NSLog (@ "OK");} else {NSLog (@ "error % d", res );}
  • NSThread

    • An NSThread object represents a thread.
  • Several ways to create a thread

  • // 1. create thread NJThread * thread = [[NJThread alloc] initWithTarget: self selector: @ selector (demo :) object: @ "jx"]; // set the thread name [thread setName: @ "ljx"]; // sets the thread priority. // The priority only indicates that the CPU is more likely to be called. [thread setThreadPriority: 1.0]; // 2. start thread [thread start];
    -Detach/performSelector + advantages: simple and fast + disadvantages: unable to set the thread in more detail ''' objc // 1. create thread [NSThread detachNewThreadSelector: @ selector (demo :) toTarget: self withObject: @ "jx"]; // 1. creating a thread // Note: This method is not available in Swift. Apple deems this method unsafe [self authentication mselectorinbackground: @ selector (demo :) withObject: @ "jx"];
  • Thread status
  • Start thread NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (run) object: nil]; [thread start]; // enter the ready status-> running status. When the thread task is completed, it automatically enters the dead state blocking (pause) thread + (void) sleepUntilDate :( NSDate *) date; + (void) sleepForTimeInterval :( NSTimeInterval) ti; // force stop thread + (void) exit when the thread is in the blocking status; // enter the dead state. Note: Once the thread is stopped (dead), the task cannot be started again.

    Security risks of Multithreading

    • The locked code can only be executed by one thread at a time.
    • @ Synchronized (Lock Object) {// code to be locked}
  • Advantages and disadvantages of mutex lock: it can effectively prevent data security problems caused by multi-thread resource snatch. Disadvantages: it consumes a large amount of CPU resources.

  • Mutex lock considerations

    • Only one lock is used to lock one piece of code. Multiple locks are invalid.
    • The larger the lock range, the worse the performance
  • Atomic and non-atomic attributes

    • Atomic: thread security, which consumes a lot of resources
    • Nonatomic: Non-thread-safe, suitable for mobile devices with small memory
  • Spin lock & mutex lock

    • In common, only one thread can execute the Code with the lock range at the same time.
    • Differences
      • Mutex lock: if other threads are found to be executing the lock code, the thread will enter the "Sleep" status and wait until other threads finish executing the lock. After the lock is opened, the thread will be "awakened"
      • Spin lock: If you find that other threads are executing the lock code, the thread will "wait" until the lock code execution is complete! Spin locks are more suitable for executing very short code!
  • Inter-thread Communication
      • The sub-thread performs time-consuming operations and the main thread updates data.
  • # Import "ViewController. h "@ interface ViewController () @ property (weak, nonatomic) IBOutlet UIImageView * imageView; @ end @ implementation ViewController-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// enable a sub-thread to download the image [self generated mselectorinbackground: @ selector (downlods) withObject: nil];}-(void) downlods {NSLog (@ "% @", [NSThread currentThread]); // 1. download image NSURL * url = [NSURL URLWithString: @ "http://pic.4j4j.cn/upload/pic/20130531/07ed5ea485.jpg"]; NSData * data = [NSData dataWithContentsOfURL: url]; // 2. convert binary to image UIImage * image = [UIImage imageWithData: data]; // 3. with the new UI # warning note: Do not update the UI in the Child thread, there will be problems/* waitUntilDone: YES: If YES is passed in, it will wait until the updateImage method is completed, will continue to execute the following code NO: If NO is passed in, it will not wait until the execution of the updateImage method is completed, you can continue the Code following * // * [self defined mselecw.mainthread: @ selector (updateImage :) withObject: image waitUntilDone: NO]; * // common in development // [self. imageView extends mselecw.mainthread: @ selector (setImage :) withObject: image waitUntilDone: YES]; // you can call the specified method of the specified object in the specified Thread [self implements mselector: @ selector (updateImage :) onThread: [NSThread mainThread] withObject: image waitUntilDone: YES];}-(void) updateImage :( UIImage *) image {NSLog (@ "% @", [NSThread currentThread]); // 3. update UI self. imageView. image = image ;}
  • GCD
  • There are two core concepts in GCD

    • Task: What operations are performed
    • Queue: used to store tasks
  • Execute task

    • Synchronization Method: dispatch_sync
    • Asynchronous Method: dispatch_async
    • Differences between synchronous and asynchronous
      • Synchronization: Only tasks can be executed in the current thread, and new threads cannot be enabled.
      • Asynchronous: You can execute tasks in new threads and enable new threads.
  • Queue

    • Concurrent queue
      • Allows concurrent (concurrent) Execution of multiple tasks (automatically enabling multiple threads to execute tasks simultaneously)
      • The concurrency function is valid only when the asynchronous (dispatch_async) function is used.
      • GCD provides global concurrent queues by default for the entire application. You do not need to manually create a global concurrent queue using the dispatch_get_global_queue function to obtain the global concurrent queue dispatch_queue_t dispatch_get_global_queue (capacity priority, // queue priority unsigned long flags); // this parameter is useless for the moment. Use 0 to obtain the global concurrent queue dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ); priority of global concurrent queue # define DISPATCH_QUEUE_PRIORITY_HIGH 2 // height # define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // default (medium) # define Queue (-2) // low # define queue INT16_MIN/background

         

    • Serial queue * allows tasks to be executed one by one (after a task is executed, the next task is executed)
    • There are two ways to obtain serial in GCD: Use the dispatch_queue_create function to create a serial queue // create a serial queue (the queue type passes NULL or DISPATCH_QUEUE_SERIAL) dispatch_queue_t queue = dispatch_queue_create. queue ", NULL); use the main queue column (queue associated with the main thread) The main queue column is a special type of serial queue that comes with GCD in the main queue column of the task, will be placed in the main thread and run dispatch_get_main_queue () to obtain the master column dispatch_queue_t queue = dispatch_get_main_queue ();
    • Notes

      Main impact of synchronization and Asynchronization: whether new threads can be enabled
      • Synchronization: Only executes tasks in the current thread and does not have the ability to enable new threads.
      • Asynchronous: You can execute tasks in new threads and enable new threads.
      Concurrency and serial mainly affect the execution of tasks.
      • Concurrency: Allows concurrent (concurrent) Execution of multiple tasks.
      • Serial: After a task is executed, execute the next task.
    • Combination of various task queues

      • Synchronization + Serial *
      • Synchronization + concurrency *
      • Asynchronous + Serial *
      • Asynchronous + concurrent *
      • Asynchronous + main queue *
      • Synchronization + main queue *
    • GCD inter-thread Communication

    • Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {// execute time-consuming asynchronous operations... dispatch_async (dispatch_get_main_queue (), ^ {// return to the main thread and execute the UI refresh operation });});
    • Other GCD usage
    • Delayed execution
    • Dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (2.0 * NSEC_PER_SEC), dispatch_get_main_queue (), ^ {// 2 seconds later, execute the code here ...});

       

    • One-time code

      • Use the dispatch_once function to ensure that a piece of code is stored inRunningExecuted only once
    • Static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// code that is executed only once (thread-safe by default )});

       

    • Fast Iteration
    • Dispatch_apply (10, dispatch_get_global_queue (0, 0), ^ (size_t index) {// execute 10 times of code, the order of index is uncertain });
    • Barrier
      • The previous task is executed only after it is executed, and the subsequent task is executed only after it is executed.
      • Cannot be a global concurrent queue
      • All tasks must be in a queue.
      • dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);
    • Queue Group
    • Dispatch_group_t group = dispatch_group_create (); dispatch_group_async (group, terminate (distinct, 0), ^ {// execute one time-consuming Asynchronous Operation}); dispatch_group_async (group, terminate (distinct, 0), ^ {// execute one time-consuming Asynchronous Operation}); dispatch_group_notify (group, dispatch_get_main_queue (), ^ {// after all the preceding asynchronous operations are completed, back to main thread ...});
    • Multi-thread implementation solution in iOS

    • Singleton Mode

      • Functions of Singleton Mode

        -During the program running process, a class has only one instance, and the instance is easy for external access, so as to conveniently control the number of instances and save system resources.
      • Use Cases of Singleton Mode

        • Share a resource in the entire application (this resource only needs to be created and initialized once)
      • Implementation of Singleton mode in ARC

      • In. m retains a Global static instance static id _ instance; override allocWithZone: method, create a unique instance here (pay attention to thread security) + (instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [super allocWithZone: zone] ;}); return _ instance ;} provides one class method for external access to a unique instance + (instancetype) sharedInstance {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [[self alloc] init] ;}); return _ instance ;}implement copyWithZone: method-(id) copyWithZone :( struct _ NSZone *) zone {return _ instance;} Note: // Note: a single instance cannot be inherited. If inheritance causes problems, // if a parent class is created first, it will always be a parent class. // If you create a subclass first, it will always be a subclass.

         

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.