IOS development-Multithreading

Source: Internet
Author: User

IOS development-Multithreading

Knowledge Point
1. Understand the concept of Thread
2. Use of NSThread
3. Use of NSOperation
4. Use of GCD
5. thread lock, thread security

====================================
1. multithreading is a technology for implementing concurrent multi-task execution. It allows multiple tasks to be executed at the same time, so as to make more reasonable use of CPU resources, improve efficiency, and prevent user interface freezing.
In iOS, all UI processing can only be performed in the main thread.

What is a process?
· Simply put, a process is an application running on our computer. Each program is a process and each process is independent, each process runs in its dedicated protected memory space (the window system can be viewed through the task manager, and the Mac system can be viewed through the activity monitor)
What is a thread?
· Through the above introduction, we know what processes are and how to run them requires threads, that is, every application wants to run, at least one thread exists. In fact, when an application is started, our system will enable a thread for our application by default. This thread is also called 'main thread ', or 'ui thread'
Relationship between processes and threads
· A thread is the execution unit. all tasks of a process are executed in a thread. For example, a process is like a department in a company. A thread represents a colleague in a department, the main thread is of course our boss. A company can have no boss, and a program cannot have no thread is actually a truth.
What is CPU?
· The CPU (Central Processing Unit) is a very large integrated circuit. It can be used to explain computer commands and process data in computer software.
Multithreading Principle
· At the same time, the CPU value can process one thread and only one thread is executing. multithreading means that multiple threads are executing at the same time. In fact, the CPU is switching between multiple threads quickly, if the time of the CPU scheduling thread is fast enough, it will lead to the illusion of multi-thread concurrent execution. When there are many threads, the efficiency of CPU switching among multiple threads will decrease, at the same time, a large amount of CPU resources are consumed, and the thread execution efficiency will decrease.
Advantages of Multithreading
· Appropriately improving program execution efficiency
· Appropriately improving resource utilization
Disadvantages of Multithreading
· Enabling a thread requires a certain amount of memory space. If a large number of threads are enabled, it will occupy a large amount of memory space and reduce program performance.
· The more threads, the higher the CPU overhead on the scheduling thread, and the more complicated the program design. Therefore, it is not recommended to open too many threads. Generally, 2 ~ 5 items are the best (and useful and cherished );
Main thread
· When an application is started, the thread created by the system by default is called 'main thread' or 'ui thread ';
· The main thread is generally used to display or refresh the UI, for example, click, scroll, drag and drop events.

====================================
2. NSThread thread control
1). Create a thread and execute it automatically
[NSThread detachNewThreadSelector: @ selector (doSomeThing) toTarget: self withObject: nil];

2 ). the creation thread does not automatically execute [[NSThread alloc] initWithTarget: self selector: @ selector (doSomeThing) object: nil]; 3 ). set thread name thread. name = @ "another thread"; 4 ). execution thread [thread start]; 5 ). thread cancelling [thread cancel]; 6 ). function to obtain the current thread [NSThread currentThread]; 7 ). obtain the main thread [NSThread mainThread]; 7 ). thread sleep [NSThread sleepForTimeInterval: 1.0f]; // sleep seconds [NSThread sleepUntilDate: date]; // sleep to the specified time 8 ). the thread exits [NSThread exit]; 9 ). thread communication [self defined mselector: @ selector (function) onThread: [NSThread mainThread] withObject: nil waitUntilDone: YES];

====================================
3. NSOperation is a task-centered multi-thread technology that does not directly manage threads.
1). NSOperation is an abstract parent class. Instead of directly using it, you should use its subclass.
NSInvocationOperation
[[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (doSomeThing) object: nil];

NSBlockOperation [NSBlockOperation blockOperationWithBlock: ^ {}]; add dependencies between tasks. The former depends on the completion of the latter, that is, the latter can be executed after execution, before adding the dependency to the queue, set [invocation addDependency: blockOperation]. If necessary, cancel [invocation cancel]. 2. NSOperationQueue, task queue, and NSOperation object must be added to the queue before they can be added to the queue, it will automatically create a thread for each NSOperation object to execute and create NSOperationQueue [[NSOperationQueue alloc] init]; and set the maximum number of concurrent queue. maxConcurrentOperationCount = 1; Add the task to the queue [queue addOperation: blockOperation]; cancel all operations in the queue [queue cancelAllOperations]; obtain the current thread's column currentQueue to obtain the main thread's column mainQueue

====================================
4. GCD is a set of C-language thread control APIs. It is the underlying implementation of NSOperation and uses Block to represent a task.
1). Create a queue
Dispatch_queue_create ("QF Queue", DISPATCH_QUEUE_CONCURRENT );

2 ). system queue dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // global queue dispatch_get_main_queue (); // main thread queue 3 ). asynchronous execution task dispatch_async (globalQuque, ^ {}); 4 ). create a group: dispatch_group_create (); 5 ). add the task to the group and run dispatch_group_async (group, globalQuque, ^ {}); 6 ). notification of group execution completion dispatch_group_notify (group, mainQuque, ^ {});

====================================
5. thread lock
1). Method 1:
_ Lock = [[NSLock alloc] init];

[_ Lock tryLock]; [_ lock unlock]; 2). Method 2: @ synchronized (self ){}

NSThread

// Multithreading -- in order to put some time-consuming operations in multiple threads for execution, it is mainly to give a good user experience and prevent the effect of freezing. // What is the better? Memory consumption and cpu usage efficiency // creates multiple threads // 1. NSThread // 2.cgd// 3. when NSOperation // is running, a thread is created by default. This thread is called the main thread/UI thread, all UI-related operations need to be performed in this thread BOOL res1 = [NSThread isMainThread]; // determine whether it is a subthread BOOL RES2 = [NSThread isMultiThreaded]; // determine whether it is a Multithreading

// 1. Create a thread Subtraction Method
// Operation-function-several lines of code-function-task
NSThread * thread1 = [[NSThread alloc] initWithTarget: self selector: @ selector (threadRun) object: nil];
// The third parameter: object. If the second parameter selector has a parameter, the object will be passed.
// The newly created thread is called a subthread or task thread/background thread

// Thread name thread1.name = @ "subthread 1"; // thread priority (double) 0-1thread1. threadPriority = 0.5; // set the thread priority (enumeration value) before enabling the thread. Otherwise, the setting is invalid. Thread1.qualityOfService = NSQualityOfServiceBackground; // 2. Enable thread [thread1 start];

// Create a thread and add a method to create and execute a thread
[NSThread detachNewThreadSelector: @ selector (threadRun) toTarget: self withObject: nil];
// If the thread name cannot be set, the thread name can be obtained through the currentThread method in the method before being assigned a value.

// NSObject method to create a thread
[Self defined mselectorinbackground: @ selector (threadRun) withObject: nil];

GCD
// GCD-a set of API Interfaces Based on C language. It adds blocks as tasks to queues for operations.

// GCD advantage: it can control the execution sequence of multiple threads. This function is not available in NSThread. // disadvantage: the thread cannot be canceled. // The GCD syntax is a C function. // 1. create a queue dispatch_queue_t queue = dispatch_queue_create (nil, DISPATCH_QUEUE_SERIAL ); // queue/thread pool // dispatch scheduling/execution // The Name Of The first parameter queue is usually nil // The Name Of The second parameter serial/parallel // DISPATCH_QUEUE_SERIAL serial sequential execution queue the thread in // DISPATCH_QUEUE_CONCURRENT executes several threads concurrently

Listening thread exit

[[Nsicationcenter center defacenter center] addObserver: self selector: @ selector (threadOut) name: NSThreadWillExitNotification object: nil]; // NSThreadWillExitNotification specifies the Exit Channel of the thread. // you only need to listen to this channel. When the thread exits, it will receive a notification/message and then call the response method. // canceling the cancel thread cannot exit a thread. the cancle method is called to notify the current thread that the isCancelled attribute is YES and to trigger the listener [thread cancel]; if (thread. isCancelled) {// If YES, you can also use return [NSThread exit];} // threadRun this method is the entry function of our sub-thread. When this method is executed, the thread is dead.

Timer

// GCD timer // 1. create a timer // you need to define the timer as a global variable or the timer will be released immediately. timer = dispatch_source_create (DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue (); // 2. set the first parameter of the timer to the interval. The second parameter is dispatch_source_set_timer (self. timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); // 3. scheduled timer operation dispatch_source_set_event_handler (self. timer, ^ {// NSLog (@ "d");}) of the timer every several seconds; // execute the timer dispatch_resume (self. timer );

Delayed operation

[NSThread sleepForTimeInterval: 2.0]; [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: 10];-(void) createQueue2 {NSLog (@ "will delay... "); // The number of seconds after which the dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (1.0 * NSEC_PER_SEC), dispatch_get_main_queue (), ^ {// DISPATCH_TIME_NOW from now on // NSEC_PER_SEC indicates the operation NSLog (@ "delayed execution");}) after the second // seconds are delayed; [self defined mselector: @ selector (afterRun) withObject: nil afterDelay: 2.0]; [NSObject cancelPreviousPerformRequestsWithTarget: self];}

Thread group

// Thread group listening thread dispatch_group_t group = dispatch_group_create (); // create a global queue = queue (0, 0); dispatch_group_async (group, queue, ^ {[NSThread sleepForTimeInterval: 2.0]; NSLog (@ "thread 1 execution completed") ;}); dispatch_group_async (group, queue, ^ {[NSThread sleepForTimeInterval: 3.0]; NSLog (@ "thread 2 finished") ;}); // The first two threads will be notified of dispatch_group_policy (group, dispatch_get_main_queue (), ^ {NSLog (@ "back to main thread ");});

Blocking thread group

Dispatch_group_t group = dispatch_group_create (); // Asynchronous Operation group dispatch_group_async (group, dispatch_get_global_queue (0, 0), ^ {for (int I = 0; I <5; I ++) {// enter the thread group dispatch_group_enter (group); [NSThread sleepForTimeInterval: 1.f]; NSLog (@ "thread --- % d", I ); // leave the thread group dispatch_group_leave (group) ;}}); // purpose: first run the preceding thread and then run the following thread // block the thread group dispatch_group_wait (group, DISPATCH_TIME_FOREVER); // Asynchronous Operation queue dispatch_async (dispatch_get_global_queue (0, 0), ^ {NSLog (@ "another thread has executed ");});
Pragma mark-repeated

-(Void) createQueue1 {
// Execute a thread repeatedly
// Number of repeated executions of the first parameter
Dispatch_apply (5, dispatch_get_global_queue (0, 0), ^ (size_t idx ){
NSLog (@ "thread execution ...");
});
}

Pragma mark-fence

-(Void) createQueue2 {

Dispatch_queue_t queue = dispatch_get_global_queue (0, 0); dispatch_async (queue, ^ {NSLog (@ "thread 1") ;}); dispatch_async (queue, ^ {NSLog (@ "thread 2") ;}); dispatch_barrier_async (queue, ^ {NSLog (@ "barrier... ") ;}); dispatch_async (queue, ^ {NSLog (@" thread 3 ");});

}

Pragma mark-semaphore

-(Void) createQueue3 {

// Semaphores // The semaphore creation parameter is Count dispatch_semaphore_t semaphore = dispatch_semaphore_create (1); dispatch_async (dispatch_get_global_queue (0, 0 ), ^ {// wait for the received signal to be written before all operations of the current thread count-1 dispatch_semaphore_wait (semaphore, DISPATCH_TIME_FOREVER); NSLog (@ "thread 1 execution... ") ;}); dispatch_async (dispatch_get_global_queue (0, 0), ^ {NSLog (@" thread 2 execution... "); // The number of sent signals + 1 dispatch_semaphore_signal (semaphore) ;}); dispatch_async (dispatch_get_global_queue (0, 0 ), ^ {NSLog (@ "thread 3 execution... ") ;}); dispatch_async (dispatch_get_global_queue (0, 0), ^ {NSLog (@" thread 4 execution... ");});

}

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.