Multiple Threads in iOS: nsunloop

Source: Internet
Author: User

1. introduction Runloop is part of the thread-related basic framework and is used to plan event processing. When there is a task, Runloop will let the thread process the task, when there is no task, Runloop will put the thread in sleep state.
Runloop management is not completely automatic. We must enable Runloop and handle the arriving events when appropriate. Both Cocoa and Core Foundation provide the Runloop object to configure and manage the Runloop of the thread. Our applications do not need to display the creation of these objects. Every thread, including the main thread of the application, has a related Runloop object. In addition, only the second thread needs to run Runloop explicitly, and the main thread does not. The APP uses the configuration and running of the main thread Runloop as part of application startup.
Two Runloop operations: 1.Nsunloop Class Reference2.CFRunLoop Reference
2. The Runloop parsing function is like its name. It enables the thread to enter a loop and calls the event processing method when the event arrives. We need to provide control statements for implementing the actual loop running of Runloop. In other words, we need to provide while or for to drive Runloop. In the loop, we run Runloop to call the event processor when the event arrives.
Runloop receives events from two origins. asynchronous distribution of Input sources is usually a message event from another thread in the same application. The distribution of Timer sources synchronization occurs at a specified time or cyclically. Both event sources use the event processing method specified by the application to process the events that arrive.

The following figure shows the concept structure of Runloop and event source. Input sources asynchronously distributes events to the responding processor, and then causes runUntilDate: (called by the thread-related Runloop object) to exit. Timer sources synchronizes distribution events to the corresponding processor but does not cause Runloop to exit.


In addition to processing Input Source events, Runloop also generates notifications of Runloop behaviors. The observer who registers the Runloop can receive the messages and then use them in the thread for additional processing. We can only use the Core Foundation interface to register the Runloop observer of a thread.

2.1 Runloop Running Mode

A Runloop running mode is a set of Input and Timer event sources to be monitored or a set of Runloop observers to be notified. Each time you run Runloop, you must specify a running mode (either explicitly or implicitly ). During Runloop running, only the source associated with the current running mode can be monitored and allowed to send events. Similarly, only the observer associated with the current running mode will be notified of the Runloop action. Sources related to other modes retain new events until Runloop runs in the appropriate mode.

In our code, we can use strings to identify the mode. Cocoa and Core Foundation define a default mode and several common and useful modes, which are identified by strings. We can use a string as the name to customize a mode. Although the name of the mode is random, the content of the mode is not random, add at least one Input source, Timer source, or Runloop observer in the mode we created.

In the special stage of Runloop, we use the run mode to filter events from the source we don't want. In most cases, Runloop runs in the default mode provided by the system, however, the Model Panel may run in "Mode". When running in this mode, only the event sources related to this mode will send the event to our thread. For the second thread, we usually use a custom mode to prevent low-priority event sources from sending events during other critical processing times.

Note: The running mode is not divided by event type, but by event source. We cannot match the mouse-down event or keyboard event through the mode, however, we can use the running mode to listen to a different set of ports, temporarily suspend Timers, or change the currently monitored event source and Runloop observer.

The following lists some standard modes defined by Cocoa and Core Foundation:

NSDefaultRunLoopMode: Default running mode, used for most operations, except for NSConnection object events. NSConnectionReplyMode: This mode is rarely used to monitor responses to NSConnection objects. NSModalPanelRunLoopMode: used to label events related to the Mode Panel. NSEventTrackingRunLoopMode: used to track the mode triggered by a touch event (for example, UIScrollView Scrolling up and down ). Nsunloopcommonmodes: A mode set. When an event source is bound to this mode set, it is equivalent to binding to each mode in the set. By Default, the Cocoa application contains the Default, Panel, and Event Tracking modes. The Core Foundation only contains the Default mode. We can use CFRunLoopAddCommonMode to add the mode. 2.2 Input Sources

Input Sources asynchronously distributes events to threads. There are two types of Input Sources: Port-based Input Sources monitor the Mach Port of the application, and custom Input Sources monitor Custom Event Sources. Nsunloop does not care about the type of the Input Source. The only difference between the two input sources is the trigger mode of the input source. The Port-based input source is triggered by the system kernel, and the custom Input Source is triggered by ourselves. When creating an input source, we add a specified mode to the input source. The following are some input sources:

2.2.1 Port-Based Sources

Cocoa and Core Foundation provide classes and interfaces to create a Port-Based source. Cocoa only needs to create an NSPort object and add it to the nsunloop. NSPort is responsible for the creation and configuration of the Input Source. Common ports and input sources that need to be manually configured for Core Foundation.

2.2.2 Custom Input Sources

We need to use the CFRunLoopSourceRef function to create an input source, and define several callback functions to configure the Input Source, process events, and delete the input source. The event trigger mechanism should be defined by ourselves.

2.2.3 Cocoa Perform Selector Sources

Cocoa defines the event source that can execute methods on any thread. The execution methods on the thread to be executed are executed sequentially, avoiding the synchronization problem of multiple methods on the thread. Perform Selector Sources will delete itself from the nsunloop after the method is executed.

Perform Selector Sources requires that the target thread's nsunloop must be running, and the main thread is running by default. In an iteration, the nsunloop process all the Perform Selector calls, instead of processing one Perform Selector call in one iteration. The Perform Selector method defined in NSObject is as follows:

Failed: withObject: Failed: modes: performSelector: onThread: Failed: modes: performSelector: withObject: afterDelay: performSelector: withObject: afterDelay: inModes: cancelPreviousPerformRequestsWithTarget: selector: object: latency execution The row is executed only when the specified delay event is passed in the next iteration of the nsunloop. The cancel operation is based on the delayed execution method.

2.3 Timer Sources

Timer Sources synchronously distributes events to our threads at a specific time in the future. Timers allows the thread to notify itself to handle some things. Timers is not a real-time mechanism. When Timers triggers the processing function, nsunloop is just executing the processing function. Timers will wait for the nsunloop to call its own processing function.

Timers can create one-time and repetitive events. When a repetitive event is created, Timers will only re-plan the trigger time based on the planned trigger time, rather than based on the exact trigger time. In addition, Timers will only trigger once because the delay trigger is lost several times.

2.4 nsunloop observer

Unlike the event source, the processing function is executed when an event is triggered. The nsunloop observer is triggered at specific points that are executed in the nsunloop. The following events can be observed in the nsunloop:

Entering the nsunloopnsunloop: the Timer event to be processed; the nsunloop event to be processed; the Input event; The nsunloop event to be sleep; The nsunloop event is awakened, but the system exits before the event is processed.

The method for creating an observer is CFRunLoopObserverRef. we can add the observer to the specified nsunloop through the Core Foundation method. The observer can also create one-time and repetitive ones. Once triggered, the observer will be deleted from the nsunloop.

2.5 order of nsunloop events

The order in which all events are handled and the notification observer is as follows:

Notify the observer that the nsunloop entry will be triggered when Timer is triggered, and notify the observer that if non-Port Input Sourc is about to be triggered by e, notify the observer to trigger a non-Port Input Source event Source. If the Port-based Input Source event Source is about to be triggered, process the event immediately, jump to Step 9 to notify the observer that the current thread will enter the sleep state and the thread will enter the sleep state until the following events occur: the Port-based Input Source is triggered, the Timer is triggered, the Run Loop runtime expires, and the Run Loop is invoked to notify the observer thread that it is about to be awakened to handle the triggered events: if it is a custom Timer, restart the Run Loop after processing the Timer event to go to step 2. If the thread is awakened and has not reached the expiration time, go to step 2. If an event occurs in another Input Source event, directly process the event. If the event arrives at this step, it indicates that the running time of the Run Loop expires, or the non-Timer Input Source event is processed, the Run Loop is about to exit. Before exiting, it notifies the observer that the thread has exited.

3. When to use nsunloop

Because the main thread's nsunloop runs automatically by default, only the second thread needs to run the nsunloop on its own. Not all threads are used to run the nsunloop. In the following situations, you need to run the nsunloop:

You need to use Port or custom Input Source to communicate with other threads. Timer needs to be used in the thread. You need to use the performSelector *** method on the thread. The thread needs to execute periodic work. NSURLConnection initiates an asynchronous request in the Child thread. 4. Supplement

4.1 thread security

Cocoa-based interfaces are NOT thread-safe, and Core Foundation-based interfaces are thread-safe.

4.2 schematic diagram of custom Input Source

Programming Part 1/3-NSThread & Run Loop

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.