iOS multithreaded Programming Guide (iii) Run loop publisher

Source: Internet
Author: User

Run loops is part of a thread-related underlying framework. A run loop is a loop of event handling that is used to keep scheduling work and handling input events. The purpose of using the run loop is to keep your threads busy working while they are working, and hibernate when they are not working.

The management of Run loop is not entirely automatic. You still need to design your thread code to start the run loop and respond correctly to input events when appropriate. Both cocoa and core fundation provide the run loop objects to help configure and manage your thread's run loop. Your application does not need to explicitly create these objects (run loop objects), and each thread, including the main thread of the program, has its corresponding run loop object. Only the worker thread needs to explicitly run its run loop. In carbon and cocoa programs, the main thread automatically creates and runs its run loop as part of the general application startup process.

The following sections provide more information about the run loops and how to configure them for your application. For additional information about run loop object, refer to the Nsrunloop Class Reference and Cfrunloop reference documentation. Analysis of 1.1 Run loop

The Run loop itself sounds like its name. It is a loop where your thread enters and uses it to run event handlers that respond to input events. Your code provides a control statement that implements the loop part, in other words, a while or a For loop statement to drive the run loop. In your loop, use the Run Loop object to run the event handling code, which responds to the received events and launches the handlers that have been installed.

The Run loop receives input events from two different sources: input source and timersource. An input source passes an asynchronous event, usually from another thread or program. A timed source passes a synchronization event that occurs at a specific time or at a repeat time interval. Both provenances use a specific process routine of the program to handle incoming events.

Figure 3-1 shows the conceptual structure of the run loop as well as various sources. The input source passes an asynchronous message to the appropriate processing routine and calls the Rununtildate: method to exit (the related Nsrunloop object invocation in the thread). The timer source passes the message directly to the processing routine, but does not exit the run loop.

Figure 3-1 Structure of a run loop and its sources

In addition to processing input sources, the run loops also generates notifications about the run loop behavior (notifications). Registered run loop observers (Run-loop observers) can receive these notifications and use them for additional processing on the thread. You can use the core Foundation to register the Run-loop viewer on your thread.

The following section describes more about the composition of the run loop, and its mode of operation. It also refers to notifications generated at different times in the handling of events. 1.1.1 Run Loop mode

The run loop mode is the collection of all input sources and timing sources to be monitored and the run Loop registration observer to be notified. Each time you run your runs loop, you specify whether it will run in a pattern, either in the display or in its implicit form. During the run loop, only the source-related sources are monitored and they are allowed to pass event messages. (Similarly, only observers associated with the schema will notify the process of the run loop). The source associated with the other schema will run only if the run loop is running in its mode, otherwise it is in a paused state.

Usually in your code, you can identify the pattern by specifying a name. The Cocoa and core Foundation define a default and some common patterns that are identified by strings in your code. Of course, you can also specify a string from the pattern name to customize the pattern. Although you can specify any name for the pattern, the contents of the schema cannot be arbitrary. You have to add one or more input sources, a timer source, or the observer of the run loop to your new model to make them valuable.

Specifying a pattern allows the run loop to filter events originating from the source at a certain stage. Most of the time, the run loop is run on the system-defined default mode. However, the modal panel (modal panel) can be run in "modal" mode. In this mode, only the source associated with the mode panel can pass messages to the thread. For worker threads, you can use a custom pattern to mask a lower-priority source delivery message on a time cycle operation.

Note: The pattern distinguishes between the source of the event and not the type of event. For example, you may not use the mode to select only the handle of mouse clicks or keyboard events. You can use the Mode listener port, pause the timer, or change the other source or in the current mode in the listening state run loop observer.

Table 1-3 lists the standard patterns defined by the Cocoa and Core Foundation, and describes when to use them. Name the column lists the constants that you use to specify the pattern in your code.

Table 3-1 Predefined Run loop modes

Mode

Name

Description

Default

Nsdefaultrunloopmode (Cocoa)

Kcfrunloopdefaultmode (Core Foundation)

The default mode is the one used for most operations. Most of the time, your should use this mode to start your run loop and configure your input sources.

Connection

Nsconnectionreplymode (Cocoa)

Cocoa uses this mode by conjunction with Nsconnection objects to monitor replies. You are should rarely need to use this mode yourself.

Modal

Nsmodalpanelrunloopmode (Cocoa)

Cocoa uses this mode to identify events intended for modal panels.

Event Tracking

Nseventtrackingrunloopmode (Cocoa)

Cocoa uses this mode to restrict incoming events during mouse-dragging loops and other sorts of user interface tracking Lo Ops.

Common modes

Nsrunloopcommonmodes (Cocoa)

Kcfrunloopcommonmodes (Core Foundation)

This is a configurable group of commonly used modes. Associating an input source and this mode also associates it with each of the modes in the group. For COCOA applications, this set includes the default, modal, and event tracking modes by default. Core Foundation includes just the default mode initially. You can add custom modes to the set using Thecfrunloopaddcommonmode function.

1.1.2 Input Source

The input source asynchronously sends a message to your thread. The source of the event depends on the type of input source: The port based input source and the custom input source . Port-based input source listener corresponding port. Custom input sources listen for custom event feeds. As for the run loop, it does not care whether the input source is a port based input source or a custom input source. The system will implement two input sources for you to use. The difference between the two types of input sources is how they are displayed: The Port-based input source is automatically sent by the kernel, whereas customizations need to be sent manually from another thread.

When you create an input source, you need to assign it to one or more patterns in the run loop. The pattern only affects the source of the listener in a particular event. In most cases, the run loop runs in the default mode, but you can also make it run in custom mode. If a source is not being monitored in the current mode, any messages it generates are not delivered until the run loop is run in its associated mode.

Port-based input sources

Cocoa and core Foundation built-in port based sources that support the use of port-related objects and functions. For example, in cocoa you never have to create an input source directly. You simply create the Port object and use the Nsport method to add the port to the run loop. The Port object handles creating and configuring the input source itself.

In the core Foundation, you must manually create the port and its run loop source. In either case, you can use a port-dependent function (CFMACHPORTREF,CFMESSAGEPORTREF,CFSOCKETREF) to create the appropriate object.

For more examples of how to set up and configure a custom port source, see the "Configuring a port-based input source" section.

Customizing input sources

In order to create a custom input source, you must use the Cfrunloopsourceref type-related function inside the core foundation to create it. You can use the callback function to configure the custom input source. The Core Fundation calls the callback function at different locations in the configuration source, handles input events, and cleans up the source when it is removed from the run loop.

In addition to defining the behavior of customizing input sources when events arrive, you must also define message passing mechanisms. This part of the source runs in a separate thread and is responsible for passing data to the source and notifying it to process the data while the data is waiting to be processed. The message delivery mechanism is defined by you, but it is better not to be too complicated.

For an example of creating a custom input source, see "Defining a custom input source." For information about customizing input sources, see Cfrunloopsource Reference.

Cocoa The source of the execution Selector

In addition to the port based source, cocoa defines a custom input source that allows you to perform selector on any thread. As with port based sources, executing selector requests is serialized on the target thread, slowing down many synchronization problems that allow multiple methods on a thread. Unlike a port based source, a selector is automatically removed from the run loop after execution.

Note: before Mac OS X v10.5, most of the execution selector may be sending messages to the main thread, but in Mac OS X v10.5 and later and in iOS, you can use them to send messages to any thread.

When selector is executed on top of another thread, the target thread must have an active run loop. For the thread you create, this means that the thread is waiting before you explicitly start the run loop. Because the main thread starts its own run loop itself, you will encounter a problem with the thread invocation when the program invokes applicationdidfinishlaunching through a delegate:. Because the run loop handles the selector invocation of all queues through each loop, instead of processing selector through the iteration of the loop.

Table 3-2 lists the selector that can be executed on other threads in NSObject. Because these methods are defined in NSObject, you can use them in any thread that can access the Objective-c object, including all threads of POSIX. These methods do not actually create a new thread execution selector.

Table 3-2 Performing selectors on the other threads

Methods

Description

PerformSelectorOnMainThread:withObject:waitUntilDone:

PerformSelectorOnMainThread:withObject:waitUntilDone:modes:

Performs the specified selector on the application ' s main thread during this thread ' s next Run loop cycle. These methods give your option of blocking the current thread until the selector is performed.

PerformSelector:onThread:withObject:waitUntilDone:

PerformSelector:onThread:withObject:waitUntilDone:modes:

Performs the specified selector on any thread for which you have an nsthreadobject. These methods give your option of blocking the current thread until the selector is performed.

PerformSelector:withObject:afterDelay:

PerformSelector:withObject:afterDelay:inModes:

Performs the specified selector on the "current thread during" Next run loop cycle and after a optional delay. Because it waits until the next run loop cycle to perform the selector, this methods provide a automatic mini delay from The currently executing code. Multiple queued selectors are performed one after another into the order they were.

Cancelpreviousperformrequestswithtarget:

CancelPreviousPerformRequestsWithTarget:selector:object:

Lets you cancel a message sent to the current thread using TheperformSelector:withObject:afterDelay:orperformSelector:wit HObject:afterDelay:inModes:method.

For more information about these methods, see NSObject Class Reference.

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.