Multithreaded Programming (iii) Nsoperationqueue

Source: Internet
Author: User

In this article, we will introduce the Nsoperationqueue in the multithreaded programming tool.

1. Nsoperationqueue Introduction

Multithreaded programming is also possible with nsoperation and Nsoperationqueue. Multithreaded programming using the Nsoperationqueue method does not create threads directly like Nsthread, and does not require management, but can indirectly intervene threads, which is also an advantage of this approach. Nsoperationqueue also introduces the concept of queue (queuing) to understand Nsoperationqueue use, first of all to understand the relationship between Nsoperation and Nsoperationqueue.

2. The relationship between the use of Nsoperation 2.1 nsoperation and Nsoperationqueue

The Nsoperation class is an abstract class that encapsulates the code and data for a single task. can refer to its English explanation:

   The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task.你使用的NSOperation类是一个抽象类来封装与单个任务相关的代码和数据

Therefore, instead of using the class directly, we use a system-defined subclass to accomplish the actual task. IOS provides two default implementations: Nsinvocationoperation and Nsblockoperation, and of course you can customize Nsoperation.

It is important to note that a subclass object that uses nsoperation can only perform one task at a time and cannot execute it again, adding him to an operations queue that we can implement using Nsoperationqueue.

2.2 How to create a nsoperation
   NSOperation是个抽象类,并不具备封装操作的能力,必须使?它的子类   使用NSOperation?类的方式有3种: (1)NSInvocationOperation (2)NSBlockOperation (3)自定义子类继承NSOperation,实现内部相应的?法。

Nsblockoperation can add new tasks through Addexecutionblock, as long as the nsblockoperation encapsulates an operand greater than 1, the operation is performed asynchronously.

Nsoperation is also designed to be extended by simply inheriting one method of overriding Nsoperation main. Then put the object of the Nsoperation subclass into the Nsoperationqueue queue, and the queue will start and process it.

   注意,需要强调的是,NSOperation默认是不执行的,需要调用start方法。同时,操作对象默认在主线程中执行,只有添加到队列中才会开启新的线程。即默认情况下,如果操作没有放到队列中queue中,都是同步执行。只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
3. Use of Nsoperationqueue

Nsoperationqueue: The nsoperation can be adjusted to start the task, but by default it is performed synchronously. If you add nsoperation to the Nsoperationqueue (action queue), the system automatically executes the operations in nsoperation asynchronously.

NSOperation和NSOperationQueue实现多线程的具体步骤:(1)先将需要执行的操作封装到一个NSOperation对象中(2)然后将NSOperation对象添加到NSOperationQueue中(3)系统会?动将NSOperationQueue中的NSOperation取来(4)将取出的NSOperation封装的操作放到?条新线程中执?

Note: A Nsoperationqueue object is not a thread, but a thread manager that can help us create new threads automatically. Depends on the maximum number of parallel queues. The Nsoperation object is added to the queue, and the default becomes asynchronous execution (not the current thread).

- 创建一个操作队列    NSOperationQueue *queue = [[NSOperationQueue alloc] init];- 添加一个operation      [queue addOperation:operation];- 添加一组operation      [queue addOperations:operations waitUntilFinished:NO];- 添加一个block形式/隐式的operation     [queue addOperationWithBlock:^() {         NSLog(@"执行一个新的操作,线程:%@", [NSThread currentThread]);     }];

After the nsoperation is added to the queue, it is usually run in a short period of time. However, if there is a dependency, or if the entire queue is paused, it may also be necessary to wait.

   注意:NSOperation添加到queue之后,绝对不要再修改NSOperation对象的状态。因为NSOperation对象可能会在任何时候运行,因此改变NSOperation对象的依赖或数据会产生不利的影响。你只能查看NSOperation对象的状态,比如是否正在运行、等待运行、已经完成等。
3. Nsoperation Order of operation

When performing a task in Nsoperationqueue, the system automatically takes out the Nsoperation object in the Nsoperationqueue and puts its encapsulated operation into a new thread to execute. If four tasks, four threads are turned on. By looking at the time the task executes, these tasks are performed in parallel.

The queue is taken out in sequence and is not contradictory to the printed result. This is like, the player a,b,c although the starting order is first A, then B, then C, but the order to reach the end is not necessarily a B in front, c in the rear.
For operations added to the queue, the order in which they are executed depends on 2 points:

    • First, let's see if Nsoperation is ready: ready to be determined by the object's dependencies?
    • It is then determined based on the relative priority of all nsoperation.
3.1 Nsoperation adding dependencies

dependencies affect the order in which the Nsoperation objects are executed in the queue, and when a Nsoperation object relies on the completion of other Nsoperation objects, one or more dependent objects can be added through the Adddependency method:

[operation2 addDependency:operation1];

The current Nsoperation object does not start until all dependent objects have completed the operation. In addition, the Removedependency method is used to delete dependent objects.

[operation2 removeDependency:operation1];

To add a prerequisite for success, you must add operation to the queue, but add dependencies before adding operation to the queue. Dependencies are not limited to nsoperation objects in the same queue. The Nsoperation object manages its own dependencies, so it is entirely possible to create dependencies between different queue nsoperation objects.

注意:唯一的限制是不能创建环形依赖,比如A依赖B,B依赖A,这是错误的
3.2 Modifying the priority of operations

The priority level is a property of the Operation object itself. By default all operation have a "normal" priority, but you can increase or decrease the priority of Operation objects by Setqueuepriority: method. The priority can only be applied to operations in the same queue. If the application has more than one operation queue, the priority level of each queue is independent of each other. Therefore, low-priority operations in different queues may still

The value of the priority level

    • Nsoperationqueuepriorityverylow = -8l,

    • Nsoperationqueueprioritylow = -4l,

    • Nsoperationqueueprioritynormal = 0,
    • Nsoperationqueuepriorityhigh = 4,

    • Nsoperationqueuepriorityveryhigh = 8

      Description: A task with high priority will have a greater chance of being called.
      Note: Priority does not replace dependencies, and priority is simply to determine the order of execution for operations that are already prepared. The dependency is satisfied first, and then the highest-priority execution is selected from all the prepared operations based on the priority.

4.4 Operational Monitoring

If you need to set a task to perform later than the B task, you can directly follow the task to write what needs to be done, such as here after downloading the picture, followed by the download of the second picture. But this writing sometimes put two unrelated operations into a code block, the code is not very readable.

With the following two methods, you can listen for an operation complete and add additional tasks.

- (void (^)(void))completionBlock;- (void)setCompletionBlock:(void (^)(void))block;

Example code:

//create object, encapsulate Operation  Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{for  ( Span class= "Hljs-keyword" >int  i=0 ; I<10 ; i++) {nslog  (@ "-operation-download picture-%@" , [nsthread  CurrentThread]); }}]; //the execution of the monitor operation is complete  operation.completionblock  =^{ Span class= "Hljs-comment" >//..... What to do after downloading a picture  nslog  (@) ;}; //Create queue  Nsoperationqueue *queue=[[nsoperationqueue Alloc]init]; //add tasks to the queue (auto-execute, auto-thread)  [Queue addoperation:operation];  
4. Related operation of Nsoperationqueue 4.1 concurrency

Concurrent Number: The number of simultaneous tasks. For example, open 3 threads at the same time to perform 3 tasks, and the concurrency number is 3.
Max Concurrency: The maximum number of tasks that can be performed at the same time.

The most significant concurrency number of the correlation? method

- (NSInteger)maxConcurrentOperationCount;- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;
   说明:如果没有设置最大并发数,那么并发的个数是由系统内存和CPU决定的,可能内存多久开多一点,内存少就开少一点。   注意:num的值并不代表线程的个数,仅仅代表线程的ID。   提示:最大并发数不要乱写(5以内),不要开太多,一般以2~3为宜,因为虽然任务是在子线程进行处理的,但是cpu处理这些过多的子线程可能会影响UI,让UI变卡。

Although the Nsoperationqueue class is designed for concurrent execution of operations, you can also force a single queue to execute only one operation at a time. Setmaxconcurrentoperationcount: Method to configure the maximum number of concurrent operations for a queue. Set to 1 to indicate that the queue can only perform one operation at a time, set the maximum number of parallel to 1 o'clock, and all op will be serial. But it does not mean that there is only one thread, and the order of execution of operation still depends on other factors, such as whether operation is ready and operation priority. Therefore, the serialized operation queue is not equivalent to the serial dispatch queue in GCD

4.2 Cancellation, pause and resume of the queue
    • Cancel all operations on a queue

      Once added to Operation Queue,queue has this operation object and cannot be deleted, the only thing that can be done is to cancel. You can call the Cancel method of the Operation object to cancel a single operation, or you can call the Cancelalloperations method of the operation queue to cancel all operations in the current queue.

      • (void) cancelalloperations;
        Tip: You can also call the Nsoperation-(void) Cancel method to cancel a single operation
    • pausing and resuming queues

      如果你想临时暂停Operations的执行,可以使用queue的setSuspended:方法暂停queue。不过暂停一个queue不会导致正在执行的operation在任务中途暂停,只是简单地阻止调度新Operation执行。你可以在响应用户请求时,暂停一个queue来暂停等待中的任务。稍后根据用户的请求,可以再次调用setSuspended:方法继续queue中operation的执行。
      • (void) setsuspended: (BOOL) b; Yes means pause queue, no for recovery queue
      • (BOOL) issuspended; Current status
        It should be emphasized that the application of pause and resume: In the TableView interface, the remote Web interface can be downloaded remotely, which will affect the UI and make the user experience worse. In this case, you can set the queue to pause (not cancel the queue) when the user operates the UI (such as scrolling the screen), to stop scrolling, and to resume the queues.
synchronous execution of 4.3 operations

The operation is placed in the queue and is executed asynchronously by default. For optimal performance, you should design your application to operate as asynchronously as possible, so that the application can handle other things while operation is executing. If you need to handle the results of operation completion in the current thread, you can use the Nsoperation waituntilfinished method to block the current thread and wait for the operation to complete. Usually we should avoid writing such code, blocking the current thread might be a simple solution, but it introduces more serial code, limits the concurrency of the entire application, and reduces the user experience. Never wait for a operation in the main thread of the application, only wait in the second or minor threads. Blocking the main thread will cause the app to fail to respond to user events, and the app will behave as unresponsive.

In addition to waiting for a single operation to complete, you can also wait for all operations in a queue, using the Nsoperationqueue waituntilalloperationsarefinished method. Note: While waiting for a queue, the other threads of the app can still add operation to the queue, so the wait time for the long thread may be added.

5. Summary:

Multithreaded programming using Nsoperationqueue is the simplest to understand in the three multithreaded programming tools commonly used in iOS, and we find that there are not too many ways to do it. But Nsoperationqueue does not do too much, and this is probably one of the reasons why it is not popular.

Multithreaded Programming (iii) Nsoperationqueue

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.