Multithreading, What Is Multithreading

Source: Internet
Author: User

Multithreading, What Is Multithreading
Multithreading 1. Definition of process 1.1

  • Process refersRunning.
  • Each process isIndependentEvery process runs in its dedicated and protected memory.
2. Definition of thread 2.1
  • A thread is the basic execution unit of a process.All tasks of a process (Program) are executed in the thread.
  • To execute a task for a process,RequiredThread required(Each process must have at least one thread)
3. Thread serial
  • The task execution in one thread isSerial (sequential execution).
  • If you want to execute multiple tasks in one thread, you can only execute these tasks one by one in order. That is to say, at the same time, one thread can only execute one task
  • Therefore, we can also considerA thread is an execution path in a process.
4. Definition of multithreading 4.1
  • Multiple Threads can be enabled in one process, and each thread canConcurrency (at the same time)Execute different tasks
    Multi-thread technology can improve program execution efficiency
4.2 multithreading Principle
  • At the same time, the CPU can only process one thread, and only one thread is working (executed)
  • Multi-thread concurrent (concurrent) execution is actually a process in which the CPU rapidly falls between multiple threads.Scheduling(Switch)
  • If the CPU scheduling thread time is fast enough, it creates the illusion of multi-thread concurrent execution.
Think: what happens if there are many threads? * The CPU is scheduled between N threads, and the CPU is exhausted, consuming a large amount of CPU resources * the frequency of scheduled execution of each thread is reduced (the thread execution efficiency is reduced)

4.3 Advantages and Disadvantages of multithreading 4.3.1 advantages of Multithreading
  • Improve program execution efficiency through concurrency
  • Resource utilization can be appropriately improved (CPU and memory usage)
4.3.2 disadvantages of Multithreading
  • To enable a thread, a certain amount of memory space is required (By default, each thread occupies kb.If a large number of threads are enabled, a large amount of memory space will be occupied to reduce program performance.
  • The more threads, the higher the CPU overhead on the scheduling thread.
  • Program Design is more complex: for example, communication between threads and multi-thread data sharing
4.4 application 4.4.1 main thread of multithreading in development
  • After an iOS program runs, one thread is enabled by default, which is called "main thread" or "UI thread"
4.4.2 role of the main thread
  • Display \ refresh UI(All operations to update the UI are executed on the main thread)
  • Handle UI events(For example, click events, scroll events, and drag events)
4.4.3 use of Multithreading
  • Do not put time-consuming operations in the main thread!Put time-consuming operations in the background thread for execution, because time-consuming operations will be stuck in the main thread, seriously affecting the UI smoothness, giving users a "card" bad experience.

NSLog is specially designed for debugging and has poor performance. In commercial software, try to remove it!

4.5 implementation scheme of multithreading in iOS

4.5.1 pthread multithreading 4.5.1.1 pthread description
  • Pthread is a POSIX multi-threaded development framework.
4.5.1.2 function prototype

Parameter description: ①. the address of the thread code in C language usually ends with _ t/Ref, and does not need to use * ②. thread attributes ③. pointer for calling the function ④. the Return Value of the parameter passed to this function is 0, indicating that the value is correct. The value is not 0, indicating that the error code is returned.

Example:

-(Void) pthreadDemo {// create thread pthread_t threadId; NSString * str = @ "Hello Pthread"; int result = pthread_create (& threadId, NULL, & demo, (_ bridge void *) (str); if (result = 0) {NSLog (@ "OK");} else {NSLog (@ "error % d ", result) ;}} void * demo (void * param) {NSString * tmp = (_ bridge NSString *) (param); NSLog (@ "% @, % @", [NSThread currentThread], tmp); return NULL ;}

Note:
* Void() (Void *)
Return Value (function pointer) (parameter)

Void * is equivalent to the id in OC.
Id (*) (id)

  • During ARC development, if the data type is designed to be the same as that in C language for conversion, use _ bridge "bridging"
  • In MRC development, bridging is not required

  • In OC, if it is developed by ARC, the compiler will automatically add retain, release, autorelease according to the code structure during compilation.

  • ARC is only responsible for the OC part of the code, not for the C code, if the C language framework contains the retain/create/copy function, all need to release
  • You can use Xcode to add a bridge!
4.5.2 NSThread implement multithreading 4.5.2.1 method 1
-(Void) threadDemo1 {// instantiate/load => alloc (memory allocation)/init (initialization) NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (demo :) object: @ "Thread"]; // start the thread [Thread start];}-(void) demo :( id) obj {for (int I = 0; I <2; I ++) {NSLog (@ "% @", [NSThread currentThread], obj );}}
4.5.2.1 method 2
-(Void) threadDemo2 {NSLog (@ "1 -- % @", [NSThread currentThread]); // detachNewThreadSelector will understand that the selector method is executed in the background thread // detach => detach a self-thread execution demo: method [NSThread detachNewThreadSelector: @ selector (demo :) toTarget: self withObject: @ "Detach"];}
4.5.2.1 method 3
-(Void) threadDemo3 {NSLog (@ "1 -- % @", [NSThread currentThread]); // is a NSObject classification method, it means that all NSObject can use this method, and the method can be executed in other threads! // Features: no thread words. Once formulated, the selector method will be immediately executed in the background thread // performSelectorInBackground implicit multi-threaded method // This method is more flexible to use! [Self defined mselectorinbackground: @ selector (demo :) withObject: @ "background"];}
4.5.2.1 Method 4
- (void)threadDemo4{    Person *p = [[Person alloc] init];    [p performSelectorInBackground:@selector(loadData) withObject:nil];}
Because-(void) implements mselectorinbackground :( SEL) aSelector withObject :( id) The arg method is the classification of NSObject objects (@ interface NSObject (nsthread1_madditions )), therefore, you can call the performSelectorInBackground method as long as it is an object that inherits NSObject directly or indirectly.
4.6 multi-thread security risks 4.6.1 scenarios with risks
  • Multiple Threads snatch the same resource.
4.6.2 Solution
  • Use mutex lock or spin lock.
4.6.2.1 mutex lock
  • 1) use format of mutex lock
    • @ Synchronized (Lock Object) {// code to be locked}
      Note: Only one lock is used to lock one piece of code. Multiple locks are invalid.
  • 2) Advantages and Disadvantages of mutex lock
    • Advantage: it can effectively prevent data security problems caused by multi-thread resource grabbing.
    • Disadvantages:Requires a large amount of CPU resources
      The lock range of the mutex should be as small as possible. The larger the lock range, the worse the efficiency!
4.6.2.2 spin lock
  • 1) atomicity and non-atomicity
    • Nonatomic: Non-atomic attribute
    • Atomic: atomic attributes (thread security) are designed for multithreading and are default attributes.
      When writing attributes to multiple threads, ensure that only one thread can perform the write operation at the same time.
      A multi-threaded technology that writes multiple (threads) reads data in a single thread. It is also possible to read dirty data again.
      In fact, there is also a lock and a spin lock inside the atomic attribute.

      Define an attribute in OC, which is usually a member variable
      If the getter & setter method of the attribute is overwritten at the same time, the _ member variable is not automatically generated!
      @ Synthesize: there were many synthesis commands before Xcode 4.5! The _ member variable is not automatically generated for attributes before Xcode 4.5!
4.6.2.3 similarities and differences between mutex lock and spin lock
  • Commonalities
    At the same time, only one thread executes the Code with the lock range.
  • Differences

    • Mutex lock: if other threads are found to be executing the lock code, the thread will enter the sleep state and wait until other threads finish executing the lock. After the lock is opened, the thread will be awakened.

    • Spin lock: if other threads are found to be executing the locked code, the thread will use an endless loop and wait until the lock code is executed completely!
      Spin locks are more suitable for executing very short code!

No matter what the lock is, you have to pay the price!

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.