Multi-threading, easy to handle multithreading

Source: Internet
Author: User
Tags gcd mutex

1. Process: An application that is running in the system

Threads: A process must be wired to perform tasks (at least one process per process)

2. Main thread: Display, refresh UI interface, handle UI events, interact with the main thread of the user

two. Several ways of multithreading (interview frequently asked)

1.Pthread: A set of common multi-threaded API, used for Unix\linux\window and other systems, cross-platform, the use of difficult, using C language, programmers manage their own life cycle.

2.NSthread: Using more object-oriented, easy to use, can directly manipulate thread objects, OC language, programmer semi-management, only with management to create, not worry about release.

3.GCD: Designed to replace threading technology such as Nsthread, leveraging the multi-core of the device to automatically manage the lifecycle

4.NSOperation: Based on gcd (bottom is gcd), more than gcd more simple and practical functions, using more object-oriented, automatic management lifecycle.

three. Thread Usage

    • Create Pthread
      • Pthread_create
    • Create a new thread as soon as it is created
    • The system automatically calls the incoming function in the child thread

      /*第一个参数: 线程的代号(当做就是线程)第二个参数: 线程的属性第三个参数: 指向函数的指针, 就是将来线程需要执行的方法第四个参数: 给第三个参数的指向函数的指针 传递的参数void *(*functionP)(void *)void *  == id一般情况下C语言中的类型都是以 _t或者Ref结尾*/pthread_t threadId;// 只要create一次就会创建一个新的线程pthread_create(&threadId , NULL, &demo, "lnj");

       

        • Nsthread
        • Several ways to create
          • First Kind
            • Alloc + init
            • Note: You need to start the thread manually
            • Feature: The current thread is retain inside the system
            • The system will not release a method until it has been executed in the thread
              // 第一种创建方式NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];

  • The second Kind
    • The system automatically starts without calling the Start method manually
    • No return value, no more settings for the thread
    • Application scenario: Quick and easy thread execution required
      [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];// 系统就会自动创建一个子线程, 并且在子线程中自动执行self的@selector方法[self performSelectorInBackground:@selector(run) withObject:nil];

       

      • Thread state

        • Create new state
        • Call Start-ready
        • Run by CPU call
        • Sleep-to-block
        • executed, or forced to close, death

          • Note: If you force the thread to close, other actions after the shutdown cannot be performed

            // 阻塞线程//  [NSThread sleepForTimeInterval:2.0];  [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]]; [NSThread exit];

    • Mutual exclusion Lock

      • Application scenario: Multi-threaded resource looting (multiple threads accessing a file/variable at the same time)
      • Note the point:
          1. As long as the shackles will consume performance
          1. If you want to really lock the code, then multiple threads must use the same lock.
          1. When locking, try to narrow the range, because the larger the range, the lower the performance.
      • Tip: If you remember a locked word quickly
        • [Nsuserdefaults Standarduserdefaults] Synchronize method of rapid memory
@synchronized(self)        {    // 需要被锁定的代码        }

    • Atomic and non-atomic properties

      • Atomic: Atomic attribute, locking for setter method (default is Atomic)
      • Nonatomic: Non-atomic attribute, does not lock the setter method
      • Note: The atomic system automatically adds a lock to us that is not a mutex/spin lock
    • Spin lock vs. Mutex lock

      • Common
        • can guarantee multiple threads at the same time, only one thread can operate a locked code
      • Different points
        • If it is a mutex, if it is locked now, then the thread in the back will go to "hibernate" state until it is unlocked and the thread continues to execute.
        • If it is a spin lock, if it is locked now, then the thread will not enter the dormant state, will always be silly wait, until after unlocking immediately execute
        • Spin lock is more suitable for short operation
  • Nsthread Inter-thread communication
    • Meaning of the Waituntildone:no parameter in the Performselectoronmainthread method
      • If yes is passed in, the code for the following lines will not continue until the method in the main thread finishes executing
      • If no is passed in, then you can continue to perform the lower of the following lines without waiting for the method in the main thread to finish executing
    • Note: The update UI must be updated in the main thread.
      [Self Performselectorinbackground: @selector (download2:) Withobject:url]; [self performselectoronmainthread: @selector (showImage:) Withobject:image waituntildone:yes]; [self performselectoronmainthread: @selector (showImage:) Withobject:image waituntildone:no]; [self.imageview performselectoronmainthread: @selector (setimage:) withobject:image waituntildone:yes];[ self performselector: @selector (showImage:) Onthread:[nsthread Mainthread] withobject:image waituntildone:YES];   
    • GCD
    • Tasks and queues

      • tasks: What to do
      • queues: Used to hold tasks
    • How to perform a task

      • synchronization function Dispatch_sync
        • does not have the ability to open a new thread
      • async function Dispatch_async
          has the ability to open new threads
      • Synchronous and asynchronous primary impact: Can I open a new thread
    • Type of queue

      • concurrent Queue
        • allows multiple tasks to execute concurrently (simultaneously)
        • Create yourself: dispatch_queue_t queue = d Ispatch_queue_create ("Com.520it.lnj", dispatch_queue_concurrent);
        • Global Concurrent Queue: dispatch_get_global_queue (0, 0);
      • serial queue
        • let the task execute one after the other
      • concurrency and serial main impact: How tasks are executed
    • Various combinations of GCD

      • asynchronous + parallel = Opens a new thread
        • asynchronous function that executes all of the code and then executes the task in the child thread
      • async + serial = Creates a new thread. But only a new thread is created, all tasks are performed in this new thread
      • synchronization + parallel = No new threads are opened
        • is actually equivalent to synchronous + serial
        • synchronization functions as long as the code executes To the line of the synchronization function, the task will be executed immediately, and only the task will continue to execute after the
      • synchronization + serial = Does not create a new thread
      • Async + Home column = does not open a new thread ul>
      • as long as the home column, always execute in the main thread
    • sync + Home column = One thing to remember: Synchronization functions cannot be used with the home column
      • Note: There are exceptions , if the synchronization function is called in an async function, then there is no problem
    • See Lesson code
    • GCD Inter-thread communication
      • Performing tasks with asynchronous functions
      • Updating the UI with the home row back to the main thread
    • The common methods in GCD
    • Deferred execution
//    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];    // 内部实现原理就是NSTimer    //    [self performSelector:@selector(run) withObject:nil afterDelay:2.0];    // 将需要执行的代码, 和方法放在一起, 提高代码的阅读性    // 相比NSTimer来说, GCD的延迟执行更加准确 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"%@", [NSThread currentThread]); NSLog(@"run");
    • Disposable code
      • During the entire program run, only one time is executed
static dispatch_once_t onceToken;     dispatch_once(&onceToken, ^{     NSLog(@"我被执行了"); });
    • Fast Iteration
/*     第一个参数: 需要执行几次任务     第二个参数: 队列     第三个参数: 当前被执行到得任务的索引     */    /*     dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index) {     NSLog(@"%@, %zd",[NSThread currentThread] , index);     });     */
    • Barrier

      • To perform all previous tasks before executing barrier, you must meet two conditions
          1. All tasks are in the same queue
          1. The queue cannot be a global parallel queue, it must be a queue created by itself
      • The tasks added before the barrier method are executed first, and only the tasks that are added before the barrier method are executed barrier
      • And if the task is added after the barrier method, it must wait until the barrier method finishes executing
    • Group

      • If you want to implement, wait for all the previous tasks to complete, and then perform a specific task, then you can gcd the middle-aged group to achieve
      • As long as all the tasks in the current group have been executed, the system will automatically call Dispatch_group_notify


Multi-threading, easy to handle multithreading

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.