Multi-Threading and Runloop

Source: Internet
Author: User

iOS development in a multi-threaded iOS program, the default 1 threads open--The main thread of Orui threads major role: Display/Refresh UI interface handle UI events (click, scroll, drag events, etc.) main thread use NOTE:do not place time-consuming operations on the main threadThe time-consuming operation should be placed on a child thread (background thread or non-main thread) in iOS with multithreaded implementations 1.pthread--POSIX thread iPhone2.0 creating a child thread: Pthread_create 2. Nsthread--A Nsthread object creates and starts a thread on behalf of a thread [[Nsthread alloc] Initwithtarget:self selector: @selector (run:) Object:nil]; [Thread start]; Main thread correlation method + (Nsthread *) Mainthread; Get the main thread-(BOOL) Ismainthread; Determines whether the main thread + (BOOL) Ismainthread; Other usage
other creation thread mode automatically starts after thread creation [Nsthread detachNewThreadSelector:toTarget:withObject:]; Auto-start after creating thread implicitly [self performselectorinbackground:withobject:]; Methods of NSObject
Thread State Block (pause) thread + (void) Sleepuntildate: + (void) Sleepfortimeinterval: Force stop Thread + (void) exit//Enter death status Note: Once the thread is stopped, the task cannot be opened again Thread SynchronizationMutex--Thread synchronization @synchronized (lock object eg:self) {//locking .... Code that needs to be locked ....one copy of the code can only be one lock .}//Unlocking inter-thread communication

3.GCD--Grand Central Dispatch "Awesome Hub Scheduler" Tasks and QueuesQueue: Used to hold a task GCD steps: Customizing tasks and adding tasks to the queue (GCD automatically take out queue tasks, putting them into the corresponding thread execution) task Removal compliance: FIFO Principle synchronization: Executing in the current thread (does not have the ability to turn on new threads) Async: Executing-----in another thread ----------------------Global Concurrent Queue:Dispatch_get_global_queueSerial queue: 1) dispatch_queue_create (); Call Dispatch_release (queue) 2 in MRC) using the primary queue (the queues associated with the mainline threads)--Dispatch_get_main_queueThe primary queue is a special serial queue with GCD, and tasks placed in the primary queue are placed in the main thread to perform GCD other usages are performed only once dispatch_once queue Group 4. Nsoperation

1> Basic Use

Nsoperation and Nsoperationqueue Implement multithreaded 2>nsoperation (abstract class) subclasses:
"Nsinvocationoperation Create and start the Action object: [[Nsinvocationoperation Alloc]initwithtarget:selector:object]; [Operation start]; New threads are not created by default, unless placed in the queue "nsblockoperation[nsblockoperation Blockoperationwithblock:]; [Operation start];//does not create a new thread by default, unless it is placed in a queue [operation addexecutionblock:];//when the number of operations in Operation >1 opens a new thread
"Custom subclasses must implement the Main method, in the main method to implement the specific operation-(void) main{...} 3> Nsoperationqueue[[nsoperationqueue Alloc]init]; [Queue addoperation:]; Automatic execution of the thread; default is concurrent execution [queue Addoperationwithblock:]
* Maximum number of concurrent settings
-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT; general 2-3 concurrency, less than 5 cancellation, pause, resume of a queue-(void) cancelalloperations-(void) Setsuspended:bool//Yes for pause, no for recovery
* Setting Dependencies
[Operationb Adddependency:operationa]; Action B relies on action A or can be set between operations on different queuesNote: cannot depend on each other Monitoring of Operationsoperation.completionblock=^{}; Runloop

The creation management Runloop cannot be displayed, each thread will have a runloop on its own, and the Currentrunloop method can get the thread corresponding to the current thread Runloop

Role

。 Keep the program running and receive user input

。 Decide when the program will handle those event

。 Call decoupling (--Message Queuing)

。 Save CPU Time

Runloops in Cocoa

Classes related to Runloop in cocoa

Nstimer, uievent,autorelease,nsdelayedperforming,nsthreadperformaddition

Cadisplaylink,catransition,caanimation,dispatch_get_main_queue (), nsurlconnnection .....

In the call stack

__cfrunloopxxxxxx functions in the call stack when Xcode is debugging

Runloop mechanism

"Cfrunlooptimer

Package of Runlooptimer

+ (Nstimer *) TimerWithTimeInterval:invocation:repeats:

+ (Nstimer *) ScheduledTimerWithInterval:invocation:repeats:

-(void) PerformSelector:withObject:afterDelay:inModes:

+ (Cadisplaylink *) Dispalylinkwithtarget:selector:

-(void) Addtorunloop:formode:

"Cfrunloopsource

Source is the Runloop data source abstract class (protocol)

Runloop defines the source of two version:

1. SOURCE0: Handle the app internal events, the app is responsible for managing (triggering) such as Uievent, Cfsocket

2. Source1: Driven by Runloop and kernel management, Mach port, such as Cfmachport,cfmessageport

"Cfrunloopobserver

"Cfrunloopmode

。 Runloop can only be and must be run in a specific mode at the same time

。 When changing mode, you need to stop the current loop and restart the new loop

。 Mode is the key to the iOS app sliding smoothly

Nsdefalutrunloopmode

Default state, Idle state

Uitrackingrunloopmode

When sliding ScrollView

Uiinitializationrunloopmode

Private, when the app starts

Nsrunloopcommonmodes

One or more of these combinations (you can define your own combination)

ScrollView Runloopmode switch when sliding: nsdefalutrunloopmode-start sliding--uitrackingrunloopmode-Stop slide--Nsdefalutrunloopmode

"The block dispatch to main queue in GCD is distributed to main runloop execution, dispatch_after the same

"Runloop suspend and wake-up

"Afnetworking creates a singleton network thread that uses Runloop to keep the thread resident (kill it after a network operation is not performed)

Does this look like only one network request sub-thread is open?

Multi-Threading and Runloop

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.