Multithreading 1-pthread and Nsthread

Source: Internet
Author: User

first, the basic content of the introduction:Process:A running program is called a process where each process is independent of each other, and each process runs within its dedicated and protected memory space.Threads:The basic execution unit that works within a program (at least 1 threads per process) thread serial: The execution of a character in 1 threads is serial (sequential) if you want to perform multiple tasks in one thread, you can perform these tasks sequentially, one at a time, i.e. A thread can only perform one task.Main thread:After an iOS program runs, the default is to turn on a thread called the "main thread" or "UI thread" function: Display \ Refresh UI interface handles UI events (such as click events, scrolling events, drag events, etc.) Use Note: 1. Don't compare More time-consuming operations are placed in the main thread 2. Time-consuming operations can get stuck in the main thread, severely affecting the smoothness of the UI, giving the user a bad experience with a card; in OC, as long as there is a string defined by @ ", if the content is the same. Everyone has the same address.Multithreading:1 processes can open multiple threads, each thread can concurrently (concurrently) perform different tasks (parallel);          Principle: 1. At the same time, the CPU can only process one thread, and only 1 threads are working (executing), 2. Multithreading concurrency (concurrent) execution is actually the CPU's fast scheduling (switching) between multiple threads.     3. If the CPU scheduler thread is fast enough, it will cause multi-threaded concurrency in the home. Advantages: Can properly improve the efficiency of the program can appropriately improve resource utilization (CPU, memory utilization) Disadvantage: Open threads need to occupy a certain amount of memory (by default, each thread occupies 512K) if you open a large number of threads, it will consume a lot of Memory space, the more threads that reduce the performance of the program, the CPU in the dispatch lineProcessThe bigger the overhead, the more complicated the programming: for example, the communication between threads, multi-threaded data sharing is the main purpose: the background operation, put in the background; The stack area is more efficient than the heap area programmer just manage the contents of the heap area two, thread classification:

1, Pthread:

1) into the header file:#import <pthread.h>

  

Create a thread, and execute the demo function in the process-(void) Pthreaddemo {/** parameter: 1> pointer to thread identifier, the end of type in C language is usually _t/ref, and does not need to use * 2> to set thread properties 3> the start address of the thread run function 4> The arguments of the run function Return value:-If thread creation succeeds, 0-returns error number if thread creation fails */pthread_t threadId =NULL;NSString *str =@ "Hello Pthread";int result = Pthread_create (&threadid,null, demo, (__bridge void *) (str)); if (result = = 0) {nslog (@ "Create thread OK"); } else {nslog (@ "Create thread failed%d", result); }}//background thread call function void *demo (void * params) {nsstring *str = (__bridge nsstring *) (params); nslog (@ "%@-%@", [nsthread CurrentThread], str); return null;} 
note:
The ' bridging ' __bridge is the arc development, when used for OC objects and C-language object conversion when the mark Arc development, the compiler will be based on the structure of the code, automatically add Retain/release/autoreleasearc is not responsible for C language memory management, If you encounter the C language frame, if the retain/copy/new appears ... Requires the programmer to release in the OC object and the C language of the pointer conversion, the need to use __bridge, to indicate what special treatment is not done; __bridge can use Xcode smart hints that the MRC does not need __bridge Because all the memory in the MRC is 2, Nsthread 1 that the programmer manages. How to create:
  (1) nsthread *thread = [[self selector: @selector (       Longoperation:) object:@ "THREAD"]; [Thread start];//mode 1 requires manual start 
(2)
[nsthread detachnewthreadselector: @selector (longoperation:) toTarget:< Span class= "Hljs-keyword" >self withobject:@ "DETACH"];
(3)
[self performselectorinbackground: @selector (longoperation:) withobject:@ "PERFORM"];
  2.线程状态:

    

Code Demo:

  

Note: Do not use exit in the main thread

3. Thread Properties

1.name thread Name: usually need to get the program to execute exactly the same thread when the program crashes

2.threadPriority threads have a priority range of 0-1.0, the default is 0.5 it is not recommended to use priority. Avoid program errors;

> Priority can only guarantee the high probability of CPU scheduling, not necessarily the first call;

The purpose of > multi-Threading is to put time-consuming operations in the background. Avoid impacting user interactions and blocking the main thread

> Development principles: Simple

3.stackSize stack Size: The size is 512k regardless of the main thread or child thread size must be an integer multiple of 4. Minimum of 8k

4.isMainThread is the main thread

4. Mutual exclusion Lock

    

Mutual exclusion Lock:

1. Guarantee the code inside the lock, the same time, only one thread can execute!

2. The locking range of the mutex should be as small as possible, the greater the lock range, the worse the efficiency! (preferably with read-write operations only)

3. Any object that can be locked NSObject

4. If there is only one place in the code that needs to be locked, it is mostly used self , which avoids creating a separate lock object

5. Note: The lock object must ensure that all threads have access to the

5. Spin Lock

Spin lock and mutual exclusion lock

The same point: to ensure that only one thread executes the lock range code at the same time;

Different points:

      互斥锁: If another thread is found to be executing the locked code, the thread 进入休眠状态 waits for the other thread to finish executing, and after the lock is opened, the thread is唤醒

      自旋锁: If another thread is found to be executing the locked code, the thread will 死循环 wait until the lock code executes (for short code)

  主线程is also known asUI 线程

Development recommendations:

All properties are declared asnonatomic

    Try to avoid multiple threads robbing the same piece of resources

As far as possible to locking, resource-grabbing business logic to the server-side processing, reduce the pressure of mobile clients

6. Communication between threads

Downloading images in a background thread

    [self performSelectorInBackground:@selector(方法名) withObject:nil];

Set the image on the main thread

    [self performSelectorOnMainThread:@selector(方法名) withObject: waitUntilDone:NO];

  

Multithreading 1-pthread and Nsthread

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.