IOS Multi-Threading management

Source: Internet
Author: User

This article describes how to create a split thread.

    • First: The method of calling NSObject directly
    • Second: Create a new thread with Nsthread
    • The third type: Create Nsoperation and add to queue Nsoperationqueue
    • Fourth type: GCD (Grand Central Dispatch) threading optimization Technology
First: The method of calling NSObject directly

All classes are subclasses of nsobject and therefore inherit these methods:

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)  Performselectoronmainthread: (sel )  aSelector Withobject: (nullable ID)  arg waituntildone: (bool )  wait; Equivalent to the first method with Kcfrunloopcommonmodes   
- (void)  Performselector: (sel )  aselector onThread:< Span class= "Hljs-params" > (nsthread  *)  thr Withobject:  (nullable ID)  arg waituntildone: ( BOOL )  wait Modes: (nullable nsarray  < nsstring  *> *)  array;   
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait);    // equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg;

The last method is executed in the background, do not use this method to modify the UI action.

The second type: Create a new thread with Nsthread 1, create a new thread with the Nsthread initialization method
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument

You need to manually open the thread after creation.

2. Create a new thread with the class method of the Nsthread class
- (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument

The thread automatically opens after creation. Regardless of which method you create, you need to use Nslock to maintain thread safety. In this nslock, the lock is the code between its lock method and the Unlock method, and once locked, the code is executed by only one thread at a time.

The third type: Create Nsoperation and add to queue Nsoperationqueue

Nsoperationqueue creates a certain number of threads to perform the nsoperation that are added to it, you can set the maximum number of threads that this queue can execute concurrently maxconcurrentoperationcount, by default, The maximum number of threads is nsoperationqueuedefaultmaxconcurrentoperationcount, and this value is automatically adapted to the system environment.

Joins the parallel execution of the nsoperation to the queue.

If you need to specify the order, you can add dependencies by adding. A Nsoperation object that executes only if its dependent Nsoperation object finishes executing.

An app can have multiple queues and each queue manages its own Nsoperation objects.
Nsoperation has many subclasses, such as Nsinnovationoperation, Nsblockoperation, which differ only in the way they are bound to the action, and the queue is treated equally.

Fourth type: GCD (Grand Central Dispatch)

GCD is a task management technology that can perform multi-core processor performance.

GCD and Nsoperationqueue are like, it also has a queue, type is dispatch_queue_t. Like Nsoperationqueue, the queue manages a number of tasks to be performed.
The difference is that the GCD is divided into parallel queues and serial queues. The serial queue executes all the tasks that are joined in one thread, while the parallel queue performs tasks similar to the Nsoperationqueue, which performs tasks with multithreading.

1. Create a queue:

(1) Direct access
The main thread of the run is also a queue in the management, this queue is the main () method of execution has been created, you can directly use this queue, and then add the task inside. Note that this queue is a serial queue.
Get the queue where the main thread is located:

dispatch_get_main_queue();

(2) Create a new queue yourself:

dispatch_queue_create(constchar *label,dispatch_queue_attr_t attr);

The first parameter is the queue name, and the second parameter determines whether the queue is a serial or parallel queue with a constant value: DISPATCH_QUEUE_SERIAL or DISPATCH_QUEUE_CONCURRENT .

2. Add tasks to the queue

The task is often added to the queue as a block.

(1) Two basic ways to add a block task
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);

The first parameter of the two method is the queue, and the second parameter is the block to be added.

The difference is that the first method is an async method, which will return the block after it is added to the queue, and the second method will wait until the joined block has finished executing.

Therefore, it is important to note that, because the main thread is listed as a serial queue, if you use the synchronous method to join the block, because the block can not rob the main thread and has not been executed, but does not execute and return, eventually causing the application to die. That is, it is best to use asynchronous methods to add tasks to a serial queue.
Although the tasks managed by the serial queue are executed serially in one thread, the serial queue and the other queues are executed in parallel.

(2) Add the method of Delay block task:
whenblock);

Whether you join a serial queue or a parallel queue, the execution is deferred.

(3) Tag grouping when adding a block task to a queue

Create groups

dispatch_group_t queueGroup= dispatch_group_create();

Add block to queue and tag grouping

groupblock);

Tasks marked grouped and without tags grouped are indistinguishable from the queue, which affects only the order in which tasks are executed relative to other tasks.

(4) Some special methods for adding block tasks.

Method One:

dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);

Blocks added in this way will become roadblocks: the task before it is added to the queue is executed before it is executed, and after it has been executed, the subsequent task can be executed. This method only takes effect on parallel queues.

Method Two:

groupblock);

When this method is executed, the block is still not in the queue, but it is registered first, and it is not really queued until the task that has been marked with the group has been completed before executing this method.

Verify that:

Combining the basic methods of adding blocks to the queue to validate the effects of these special methods ():

A new parallel queue was created in the code and a new grouping was created.

Several blocks are then added to this queue, named Task 1~ Task 7, in the order in which the methods are executed.

Task 1 and Task 4 are labeled grouped, others are not marked, Task 3 is a roadblock, task 6 is preceded by a task that marks the same grouping before the queue is joined. The tasks are executed in principle in parallel.

Operation Result:

As you can see from the running results,
Task 1 and Task 2 are joined to the queue before task 3 (roadblocks), so they are executed before task 3.
Tasks 4, 5, and 7 are executed in parallel.
Task 6, such as Task 4, is marked with the same grouping before joining the queue.

IOS Multi-Threading management

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.