Overview and use of iOS multithreading scenarios

Source: Internet
Author: User

This article has compiled several of the main multithreaded scenarios in iOS, providing a way to write Swift and Objective-c in two languages.

Overview

iOS currently has four multithreading solutions:

    • Nsthread
    • GCD
    • Nsoperation
    • Pthread

Pthread This scheme is too low-level, the actual development is seldom used, the following main introduction of the first three scenarios

Nsthread

Nsthread is a thread-based, lightweight multithreaded programming approach (relative to GCD and Nsoperation), a Nsthread object that represents a thread, needs to manually manage the thread's life cycle, handle thread synchronization, and so on.

Create a methodobjective-c:

Creating and starting a thread

// Initializing Threads Object : nil]; // Start Thread [Thread start];

Or start directly after creation

[Nsthread detachnewthreadselector: @selector (run:) totarget:self Withobject:nil];
Swift:
// Create " threadfunction: " Object : nil) // start Thread.Start ()

Or

NSThread.detachNewThreadSelector("run:", toTarget: self, withObject: nil)

OC also has a method of creating threads and starting directly using the NSObject method

[Self Performselectorinbackground: @selector (run:) Withobject:nil];

In Swift, Apple has removed this method due to security concerns.

a few other common methods
//get current thread information+ (Nsthread *) CurrentThread;//get the main thread information+ (Nsthread *) Mainthread;//Cancel Thread- (void) Cancel;//Get thread State@property (ReadOnly, getter=isexecuting) BOOL executing; @property (ReadOnly, getter=isfinished) BOOL finished; @property (ReadOnly, getter=iscancelled) BOOL cancelled;//set and get the thread name-(void) SetName: (NSString *) n;-(NSString *) name;//pauses the current thread for a period of time, or pauses to a moment+ (void) Sleepfortimeinterval: (nstimeinterval) time;+ (void) Sleepuntildate: (NSDate *) date;

Swift's method names and invocation methods are basically consistent with OC, which is not listed here.

GCD

Grand Central Dispatch (GCD) is a relatively new solution for multi-core programming developed by Apple. It is primarily used to optimize applications to support multicore processors as well as other symmetric multi-processing systems.

GCD is an efficient and powerful technology that replaces technologies such as Nsthread. GCD can handle complex asynchronous programming issues such as data locking and resource leaks. GCD works by letting a program schedule them to perform specific tasks in parallel on any available processor core, depending on the available processing resources. This task can be a function or a program segment.

Simply put, GCD will automatically manage the thread life cycle (Create, dispatch, destroy), we just have to tell it what to do, the other things it will help us, is it convenient?

To understand how GCD is used, first understand the four concepts: task, queue, synchronous execution, asynchronous execution

task: in GCD, a task can be understood as a block code, which is the action you want to perform.

Synchronous Execution (synchronous dispatch): The task executes sequentially one at a the same thread, and the next task does not begin until the previous task finishes executing. In other words, the current thread is blocked.

Asynchronous Execution (asynchronous dispatch): the task executes in a different thread, and the next task does not start until the previous task has finished executing. In other words, the current thread is not blocked.

queue: A pool of resources used to place tasks and remove and perform tasks according to certain rules. Queues are divided into serial queues and parallel queues .

    • Serial queue: follow FIFO (first-in-one-out) principle one takes out a task and executes it, and the previous task is completed before the next task is taken and executed. Whether synchronous or asynchronous, the serial queue is an execution task, meaning that the tasks in the same serial queue are executed in the same thread.
    • Parallel queue: also follows FIFO principle one takes out a task, the difference from a serial queue is that a new thread is opened and executed in a new thread. tasks in the same parallel queue are typically executed in different threads
Queues are executed differently, resulting in different effects
Synchronous execution Asynchronous execution
Serial queue Blocks the current thread until the tasks in the serial queue are executed. The system does not start another thread, and the current thread executes the task one by one. does not block the current thread, the system will start a new thread and perform the task sequentially one by one in the new thread.
Parallel queues Blocks the current thread until the synchronous dispatch task in the parallel queue is completed. The system does not start another thread, and the current thread executes the synchronously dispatched task sequentially. does not block the current thread, the system will start a new thread and execute, and each additional asynchronous dispatch of the task system will open one more thread.

The formation of the deadlock

A deadlock is formed when a task is added to the serial queue where the current thread is in a synchronous dispatch. Because synchronous dispatch blocks the current thread until the dispatched task execution completion thread resumes execution. The dispatched task happens to be joined by the currently blocked thread, which causes the task to fail to execute (because the thread of the task is blocked), thus forming a deadlock.

Create queue 1, home row

This is a system-defined serial queue, and any task that refreshes the UI takes place in the main queue. Therefore, try not to add time-consuming tasks to the main queue, ensuring that the task of refreshing the interface is not blocked, giving the user a smooth interaction experience.

// objective-cdispatch_queue_t queue = ispatch_get_main_queue (); // SWIFTLet queue = Ispatch_get_main_queue ()
2. Custom queue

You can create a serial or parallel queue, and the second parameter passes dispatch_queue_serial or NULL to a serial queue and dispatch_queue_concurrent to a parallel queue.

//objective-c//Serial Queuedispatch_queue_t queue = Dispatch_queue_create ("SerialtEstqueue", NULL);d ispatch_queue_t queue= Dispatch_queue_create ("Serialtestqueue", dispatch_queue_serial);//Parallel Queuesdispatch_queue_t queue = Dispatch_queue_create ("Concurrenttestqueue", dispatch_queue_concurrent);//SWIFT//Serial QueueLet queue = Dispatch_queue_create ("Serialtestqueue", nil); let queue= Dispatch_queue_create ("Serialtestqueue", dispatch_queue_serial)//Parallel QueuesLet queue = Dispatch_queue_create ("Concurrenttestqueue", dispatch_queue_concurrent)
3. Global Parallel queue

This is a system-defined parallel queue in which parallel tasks are typically added to this queue.

// objective-c 0 ); // SWIFT 0)
Create Task 1, Sync Dispatch (Sync)

Synchronous dispatch will block the current thread. Regardless of whether the dispatch task is synchronized to a serial or parallel queue, no new threads are available and only the task is executed in the current thread. Note that if the current thread is executing in a serial queue, the task cannot be dispatched to this queue in the current thread, or a deadlock will be formed.

// objective-cDispatch_sync (< #传入队列 #>, ^{      //Execute code block }); // SWIFT inch      //EXECUTE code block })
2. Asynchronous dispatch (Async)

Asynchronous dispatch does not block the current thread. When the task is dispatched asynchronously to the queue that is not the current thread , the system must start a new thread, and there are two cases when dispatching the task asynchronously to the queue where the current thread is located: 1. If the current thread is in a serial queue, the system will not start a new thread. The added task will not execute (FIFO) until the previous tasks in the queue have been completed, 2, if the current thread is in a parallel queue, the system will start a new thread, and the added task will be executed concurrently with the other tasks in the queue.

// objective-cDispatch_async (< #传入队列 #>, ^{      //Execute code block }); // SWIFT inch      //EXECUTE code block })
Queue Group

Queue groups can add different types of queues to a group, and there is a callback method when all the queues are executed:

// objective-cdispatch_group_notify (Group, Dispatch_get_main_queue (), ^{    NSLog (@ ) the tasks in the queue are complete " );}); // SWIFT inch     NSLog (" the task is completed in the Yes ")}
Other practical methods

func dispatch_barrier_async(_ queue: dispatch_queue_t, _ block: dispatch_block_t):

When the first parameter is passed to a custom parallel queue, the added task blocks the queue, and when the task in front of it executes, the task is executed, and the blocking state of the queue is canceled when the task is completed, and when the first parameter is passed to a value of other cases, This method works the same as Dispatch_async.

func dispatch_barrier_sync(_ queue: dispatch_queue_t, _ block: dispatch_block_t):

When the first parameter is passed to a custom parallel queue, this method acts like the previous method, except that this method also blocks the current thread, and that the method acts as Dispatch_sync when the first parameter passes in a value other than the other.

Nsoperation

Nsoperation is actually the encapsulation of GCD in an object-oriented manner.

Task->nsoperation Queue->nsoperationqueue

Add a task

Nsoperation is a base class that has two subclasses: NSInvocationOperation andNSBlockOperation。创建任务后需要调用start方法来启动任务,默认再当前队列同步执行。可以在中途调用cancel方法中止任务的执行。

Nsinvocationoperation

Objective-c

// 1. Create an Object Object : nil]; // 2. Start Execution [Operation start];

Because of security issues, Swift cannot use this class

Nsblockoperation
//objective-c//1. Create an ObjectNsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%@", [Nsthread CurrentThread]);}];//2. Start a task[Operation start];
//--------------------------------------------------//
//SWIFT//1. Create an ObjectLet operation = nsblockoperation {()-Voidinchprintln (Nsthread.currentthread ())}//2. Start a taskOperation.start ()

So how do you do tasks in parallel? NSBlockOperationThere is one way:addExecutionBlock:可以给一个Opertion添加多个任务,这些任务会并行执行

Objective-c:

//1. Create a Nsblockoperation objectNsblockoperation *operation = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%@", [Nsthread CurrentThread]);}];//Add multiple block for(Nsinteger i =0; I <5; i++) {[Operation Addexecutionblock:^{NSLog (@"§%ld:%@", I, [Nsthread CurrentThread]); }];}//2. Start a task[Operation start];

SWIFT:

//1. Create a Nsblockoperation objectLet operation = nsblockoperation {()-VoidinchNSLog ("%@", Nsthread.currentthread ())}//2. Add multiple block forIinch 0.. <5{operation.addexecutionblock {()-VoidinchNSLog ("§%ld-%@", I, Nsthread.currentthread ())}}//3. Start a taskOperation.start ()

Note: addExecutionBlock the method must be start() executed before the method, or it will be an error.

Custom operation you can customize operation in addition to the two operation above. InheritedNSOperationclass, and implement itsmainmethod, because the call to thestartmethod, the internal calls themainmethod to complete the relevant logic. In addition, you need to implementcanceland other methods. Create a queue

The Start method that calls operation is executed synchronously, that is, it blocks the current thread, how does it execute asynchronously? We're going to use a queue here Nsoperationqueue

Primary queue

This is a system-defined queue, and any task that refreshes the UI takes place in the main queue. In order to give the UI experience to the user process, the thread priority in the primary queue is the highest. The tasks in this queue are executed serially.

// objective-c Nsoperationqueue *queue = [Nsoperationqueue mainqueue]; // SWIFTLet queue = Nsoperationqueue.mainqueue ()
Other queues

The custom queue is the other queue. By default, tasks for other queues are executed in parallel in different threads. It has a parameter maxconcurrentoperationcount maximum concurrency, which is used to set the maximum number of parallel tasks that can be executed concurrently. Setting it to 1 indicates that this is a serial queue.

// objective-c Creating additional queues Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; // Swift creates additional queues let queue = Nsoperationqueue ()
Add a task
// objective-c Adding tasks to the queue [Queue addoperation:operation]; // Swift adds a task to the queue queue.addoperation (operation)

When you add a task to a queue, it automatically starts executing without calling start.

There is also a way to add a task that adds a -(void)addOperationWithBlock:(void (^)(void))block; 可以直接往 block of code that you want to execute to the queue without creating a operation.

adding dependencies

When task a must be completed before task B can start executing, add a dependency B.

[Operationa ADDDEPENDENCY:OPERATIONB];

Note: 1, can not add dependencies (a dependent on b,b dependency a), which will form a deadlock, 2, the use of removedependency to release the dependency; 3. You can add dependencies to tasks in different queues.

Other methods Nsoperation
// determine if the task is executing  // determine if the task completed void (^completionblock) (void//  Used to set the action to be performed after completion -(void // Cancel Task -(void/ / Blocks the current thread until the task finishes
Nsoperationqueue
// Get Queue Task Count -(void/ /Cancel All tasks in Queue -(void//  Block the current thread until all tasks in this queue have been completed  //  pause queue//  continue queue
Thread synchronization

When a thread is operating on a resource in memory, no other thread can manipulate the resource until the thread finishes the operation. This is done primarily to ensure the security and reliability of some resource data.

Implementing thread synchronization can take the following approach:

Mutual exclusion Lock
// objective-c @synchronized (self) {    // code block to execute }//SWIFTObjc_sync _enter (self)// code block objc_sync_exit (self) to execute
Synchronous execution

You can use the serial queue knowledge described above to add each code that accesses this resource to the same serial queue, so that thread synchronization can be implemented.

Summarize

The first time to write a blog, the knowledge you used to summarize, or very useful. Later will write more things to share to everyone, but also convenient for their own inspection.

Thanks to the author of the book, Bourne's Legacy (http://www.jianshu.com/p/0b0d9b1f1f19) has given me a lot of help.

Overview and use of iOS multithreading scenarios

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.