IOS: A detailed introduction to multithreading

Source: Internet
Author: User

Multithreading:first, the concept
1. What is a process? A one-time execution of a program is a process. The process occupies a separate memory space.   2. What is a thread? the execution path of the code in the process.   3. What is the relationship between process and thread? each process has to create a thread called the main threads. The main thread is the parent thread of all other threads. Multiple threads share memory space between processes.   4, single core and multi-core processor under the different multithreading? Single-core processors: A CPU is a split-time slice that takes turns executing different threads, which need to be saved and the context of the restorer thread (the contents of the registers in the CPU) when switching threads. multicore processors: Multiple CPUs can execute different threads at the same time.   5, multi-threaded thread synchronization problem? thread synchronization Occurs when multiple threads are competing against the same resource. Workaround: Locking lock, conditional condition, semaphore Semaphore (producer consumer issues)  

Two, 3 kinds of multithreading technology comparison

1.NSThread 2.NSOperation 3.gcd--grand Central Dispatch, a framework based on C language

These three ways of programming from top to bottom, the level of abstraction from low to high, the higher the abstraction of the more simple to use, is also the most recommended for Apple. But for now, iOS developers need to be aware of the basic use of three of multithreaded technologies. Because many of the framework technologies use different multithreading techniques, respectively. For example Nsurlconnection Async static method: Sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *error)

Nsthread: Pros: Nsthread than the other two lightweight, easy to use Cons: You need to manage your thread's lifecycle and thread synchronization. Thread synchronization has a certain overhead in locking data nsoperation: no need to care about thread management, data synchronization, you can focus on what you need to do GCD: The Grand Central Dispatch is a multi-core programming solution developed by Apple. Ios4.0+ can be used as an alternative to Nsthread, Nsoperation's efficient and powerful technology, widely used, and a framework that Apple strongly advocates.
     

Iii. main 3 ways to create threads

to create a threading method:
1.+  (void) Detachnewthreadselector: (SEL) Selector totarget :(ID) Target withobject: (id) argument; 2.-(ID) Initwithtarget: (ID) Target selector: (SEL) Selector object: (ID) argument; 3. Inherits the Nsthread class, and then overrides the main method of the parent class's execution thread in the subclass.   parameter description: selector: Thread execution method, can have only one parameter, cannot have return value target:selector message Sent object argument: The only parameter transmitted to target, or nil NSObject directly joined the multi-threaded support, Allows a method of the object to run in the background (this method is commonly used in the game, the use of multi-threaded play sound)  -(void) Performselectorinbackground: (SEL) Aselector withobject: (ID) arg;  

Iv. Use of Nsthread

• When it comes to shared resource contention, data locking of shared resources is a difficult problem, which ensures data security while ensuring thread execution efficiency – Lock before use – Use as soon as possible – Unlocked after use – To do other things • Multithreaded Authoring sequence 1. Single Method debug OK 2. Single Thread debug OK 3. Increase the thread and consider the exact position of the line Cheng and unlocking. • Note: – Only the main thread can modify the UI – If memory scramble is not involved, nsthread writing multithreading is the simplest • • Using the NSObject Performselectorinbackground method is a very convenient way to implement multithreading when no shared resource contention is involved
 

v. Use of Nsoperation & Nsoperationqueue

two subcategories of nsoperation 1.NSInvocationOperation 2.NSBlockOperation 3. Subclass the Nsoperation, and then override the Main method • Operating principle: 1. Encapsulating the action to be performed with the Nsoperation 2. Put the created Nsoperation object in the Nsoperationqueue 3. Start Operationqueue operations in the new thread execution queue • Precautions: 1. Multi-Threading is often required to control the number of concurrent threads because threads consume system resources, run too many threads, and the system slows down 2. Use the following methods to control the number of concurrent threads:

-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT

• Use summary:

No need to use a thread lock in nsoperation

• In addition to updating the UI, contention for shared resources also needs to be placed in the main thread queue

• Multithreading starts when a defined action is added to the queue

Nsblockoperation is more flexible and easy to use than nsinvocationoperation

• The maximum number of concurrent threads can be controlled by the Setmaxconcurrentoperationcount method

Vi. Use of GCD

GCD is a C language-based framework
• Operating principle:
– specific tasks that allow the program to queue in parallel, scheduling them to perform tasks on any available processor, based on available processing resources
– The task to be performed can be a function or a block
– The bottom layer is implemented by threading, but programmers don't have to focus on the details of the implementation
the FIFO queue in –GCD is called the dispatch queue, which guarantees that advanced tasks are executed first
.
–dispatch__notify can be used to monitor whether a set of tasks are completed and notified after completion
Dispatch queue:
1.Main Dispatch queue: The globally available queues for performing tasks on the main
thread
2.Serial: perform only one task at a time
3.Concurrent: Multiple tasks can be executed concurrently, but the order of completion is random
• Use summary:The gcd principle is very similar to operation, except that it is a C-language architecture. no need to use a lock in gcd • In addition to updating the UI, contention for shared resources also needs to be placed in the main dispatch queue • Add tasks to groups and specify global operations queues, making GCD multithreading more flexible and convenient Dispatch_group_notify can listen to whether a set of tasks is complete. This method is useful, for example, you perform three download tasks, and when three tasks are downloaded, the interface is said to be completed • If you do not need to listen to a set of tasks, you can use the Dispatch_async method directly

Final recommendations:

• Three key points to keep in mind about multithreading– UI can only be updated in the main thread– Processing of shared data contention– Don't use multiple multithreading techniques to compete for the same resource! • When using multithreading, it is to handle concurrent operations. If it is possible, we do not do to rob the resources of the matter!

 

IOS: A detailed introduction to 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.