I. Definition of Runloop
When there is a continuous demand for asynchronous tasks, we create a separate life-cycle controllable thread. Runloop is the mechanism for controlling the thread life cycle and receiving events for processing.
Runloop is the most central mechanism for iOS incident response and task handling, which runs through the entire iOS system.
Foundation:nsrunloopcore foundation:cfrunloop Core section, code Open source, C language writing, cross-platform
Second, the purpose
Power saving through runloop mechanism, smooth, fast response, good user experience
Third, understanding
Process is a factory, the thread is a pipeline, run loop is the head of the pipeline, when the factory received orders assigned to this assembly line, run loop to start the assembly line, let the assembly line moving, production products; When the product is finished, the run loop will temporarily stop the assembly line, Conserve resources. Runloop Management pipeline, assembly line will not be destroyed by the factory idle, and do not need the assembly line, will be dismissed Runloop this supervisor, that is, the exit process, the release of all resources.
Runloop is not the exclusive concept of the iOS platform, in the multi-threaded programming of any platform, in order to control the life cycle of the thread, receive processing asynchronous messages need a similar runloop loop mechanism implementation, Android Looper is similar mechanism.
Iv. characteristics
-
The runloop of the main thread is automatically created when the app is launched
-
Other threads need to start themselves under that thread
-
You cannot create runloop yourself
-
Runloop is not thread-safe, so you need to avoid invoking the current thread's runloop on other threads
-
Runloop is responsible for managing autorelease pools
-
Runloop is responsible for handling message events, i.e. input source events and timer events
Runloop mechanism
The main thread (threads with runloop) almost all functions are redeployed from one of the following six functions:
-
Cfrunloop_is_calling_out_to_an_observer_callback_function
Cfrunloop is calling-Abserver callback function
For external reporting of changes to the current state of Runloop, many mechanisms in the framework are triggered by runloopobserver, such as Caanimation
-
Cfrunloop_is_calling_out_to_a_block
Cfrunloop is calling off to a block
Message notifications, non-deferred perform, dispatch calls, block callbacks, KVO
-
Cfrunloop_is_servicing_the_main_dispatch_queuecfrunloop is servicing the MAIN Desipatch queue
-
Cfrunloop_is_calling_out_to_a_timer_callback_function
Cfrunloop is calling off to a timer callback function
Deferred perform, deferred dispatch call
-
Cfrunloop_is_calling_out_to_a_source0_perform_function
Cfrunloop is calling off to a source 0 perform function
Handle app internal events, the app is responsible for managing (triggering), such as Uievent, Cfsocket. Normal function call, system call
-
Cfrunloop_is_calling_out_to_a_source1_perform_function
Cfrunloop is calling off to a source 1 perform function
Managed by Runloop and kernel, Mach port drives, such as Cfmachport, Cfmessageport
Runloop Frame:
Runloop Run Time:
Runloop mainly has the following six states:
-
Kcfrunloopentry--Entering the Runloop cycle
-
Kcfrunloopbeforetimers--Handle callback before timing call
-
Kcfrunloopbeforesources--handling of input sources events
-
Kcfrunloopbeforewaiting--Runloop call before sleep
-
Kcfrunloopafterwaiting--Runloop wake-up call
-
Kcfrunloopexit--Exit Runloop
Runloop run-time Call stack
Main thread App Runtime
The relationship between Runloopobserver and Autorelease pool
UIKit the Autorelease object produced in this Loop by Runloopobserver the Pop and Push of the autorelease Pool between two Sleep Runloop
Runloop suspend and wake-up:
Specify the Mach_port port for wake-up
Call the Mach_msg listener wake-up port, the system kernel hangs the thread before it wakes up, and stays in the Mach_msg_trap state.
After the msg of this port is sent to the kernel by another thread, the trap state is awakened and Runloop continues to work.
Runloop supported message events (events)
-
Runloop
-
Support for receiving processing input source events, including:
The Mach port event of the system, which is a custom input event for communication events
-
Support for accepting processing timing source (timer) events
-
Before starting Runloop, you must add a listener input source event or timing source event, otherwise the call [Runloop Run] will return directly without going into the loop to keep the thread in the long-standing.
If no input source event or timer event is added, the thread will always be in an infinite loop idling, occupying CPU time slices and not achieving a reasonable allocation of resources. Threads that do not have a while loop and do not add any input source or timer are directly completed and reclaimed by the system.
//Error ProcedureNsrunloop *runloop=[Nsrunloop Currentrunloop]; while(!self.iscancelled &&!)self.isfinished) {[Runloop rununtildate:[nsdate Datewithtimeintervalsincenow:3]]; }; //Correct PracticeNsrunloop *runloop =[Nsrunloop Currentrunloop]; [Runloop Addport:[nsmachport Port] Formode:nsdefaultrunloopmode]; while(!self.iscancelled &&!)self.isfinished) {@autoreleasepool {[runloop rununtildate:[nsdate Datewithtimeintervalsincenow:3]]; } }Run Loop Modes
-
Understanding the Run Loop mode is the type of product that is supported on the production line, and the pipeline can only run in one mode at a time, producing a certain type of product. A message event is an order.
-
Cocoa defines the four mode
Default:nsdefaultrunloopmode, the default mode, which is run by default when no mode is specified in the run loop
Connection:nsconnectionreplymode, which listens for events that handle network request Nsconnection
Modal:nsmodalpanelrunloopmode,os The modal panel event for X,
Event Tracking:uitrackingrunloopmode, drag event
Common Mode:nsrunloopcommonmodes, is a collection of patterns, When binding an event source to this collection of patterns is equivalent to binding to each pattern within the collection
-
Runloop can be passed [acceptinputformode:beforedate:] and [RunMode: Beforedate:] To specify the operating mode for a period of time. If not specified, Runloop defaults to run under Default (repeatedly calling Runmode:nsdefaultrunloopmode Befordate:)
-
To start a timer timer on the main thread, Then drag UITableView or Uiscrollview, and the timer does not execute. This is because, for a better user experience, the event tracking mode has the highest priority in the main thread. When the user drags the control, the main thread's run loop is run under event tracking mode, and the timer created is defaulted to default mode, so the system does not immediately execute the event received under default mode. Workaround:
Nstimer*timer=[nstimer scheduledtimerwithtimeinterval:target:self selector: @selector ( Timerfiremethod:) Userinfo:nil Repeats:yes]; [[Nsrunloop Mainrunloop]addtimer:timer formode:nsrunloopcommonmodes]; // or [[Nsrunloop Currentrunloop] Addtimer:timer Formode:uitrackingrunloopmode]; [Timer fire];
Run Loop Application Practice
There are three main scenarios for the Run loop:
nsrunloop*runloop=[Nsrunloop Currentrunloop]; [Runloop Addport:[nsmachport Port] formode:nsdefaultrunloopmode]; while (!self.iscancelled&&! self.isfinished) { @autoreleasepool { [runloop rununtildate:[nsdate datewithtimeintervalsincenow:3]]; } }
- Create a resident thread to perform some of the tasks that will persist. The thread's life cycle is the same as the app
@autoreleasepool { *runloop=[Nsrunloop currentrunloop]; [Runloop Addport:[nsmachport Port] formode:nsdefaultrunloopmode]; [Runloop run]; }
- A thread that listens for an event, or performs a certain task, in a certain amount of time, with the following code, executing ontimerfired every 30s in 30 minutes:. This scenario typically occurs when I need to continuously update an item for a certain amount of time after the app starts.
@autoreleasepool { *runloop = [Nsrunloop currentrunloop]; *udpatetimer = [Nstimer timerwithtimeinterval: target:self selector: @selector (ontimerfired:) userInfo : nil Repeats:yes]; [Runloop Addtimer:udpatetimer formode:nsrunloopcommonmodes]; [Runloop rununtildate:[nsdate datewithtimeintervalsincenow: []]; }
Creation of Runloop in afnetworking:
+(void) Networkrequestthreadentrypoint: (ID) __unusedobject{@autoreleasepool {[[Nsthread CurrentThread] SetName:@"afnetworking"]; //This is mainly to listen to a port, so that this thread does not recycle
[Runloop Addport:[nsmachport Port] formode:nsdefaultrunloopmode];Nsrunloop *runloop=[Nsrunloop Currentrunloop]; [Runloop Run]; }}+ (nsthread*) networkrequestthread{StaticNsthread *_networkrequestthread =Nil; Staticdispatch_once_toncepredicate; Dispatch_once (&oncepredicate,^{_networkrequestthread= [[Nsthread alloc] initwithtarget:self selector: @selector (networkrequestthreadentrypoint:)Object: nil]; [_networkrequestthread start]; }); return_networkrequestthread;}
IOS Runloop Understanding