I. Thread creation:
Operation objectis may create threads faster. For details, refer to: iOS core system programming best practices: concurrency.
1. Thread creation requires a large amount of memory and time consumption. Therefore, we recommend that you use the entry point function to do a considerable amount of work, or create a Run Loops to allow regular work.
2. Run Loops allows you to create long-running threads with the smallest resources. Run loop puts its thread in sleep state without any event processing. It eliminates CPU cycle polling consumption and prevents the processor from sleep and saves power.
3. to configure the run loop, you need to start your thread, get the object reference of the run loop, set your event handler, and tell the run loop to run. The infrastructure provided by Cocoa and Carbon automatically configures the corresponding run loop for your main thread. If you want to create a long-running auxiliary thread, you must configure the corresponding run loop for your thread.
4. Each thread has its own RunLoop, but by default, the RunLoop of a non-main thread does not run. You need to add at least one event source for the RunLoop and then run it. Generally, we do not need to enable the RunLoop of a thread unless you need to detect an event for a long time in a separate thread.
5. RunLoop is a loop, but many features are added to this loop. First, you need to check whether there are any events to be processed at the beginning of the loop body. If yes, you need to process them. If not, you need to sleep to save CPU time. Therefore, the focus is on the event to be processed. In RunLoop, there are two types of events to be processed: one is the input source and the other is the timer, timers are the operations that require scheduled execution. The input sources are classified into three types: mongomselector sources, Mach port-based sources, and custom sources. You can add your own source when programming. RunLoop also has the concept of Observer. You can add your own Observer to RunLoop to monitor the running process of RunLoop. CFRunLoop. h defines the types of all observers:
[Html]
Enum CFRunLoopActivity {
KCFRunLoopEntry = (1 <0 ),
KCFRunLoopBeforeTimers = (1 <1 ),
KCFRunLoopBeforeSources = (1 <2 ),
KCFRunLoopBeforeWaiting = (1 <5 ),
KCFRunLoopAfterWaiting = (1 <6 ),
KCFRunLoopExit = (1 <7 ),
KCFRunLoopAllActivities = 0x0FFFFFFFU
};
Typedef enum CFRunLoopActivity;
If you have used a select System Call and written a program, you can quickly understand the concept of the runloop event source. Essentially, the event source mechanism is similar to select, which is a multiplexing IO implementation, in a thread, what we need to do is not a single task. If we need to process clock events, we need to process user touch events, and we need to accept data sent from the remote network, register all the things that need to be done in the event source, and check whether the event source has the data to be processed at the beginning of each loop. If so, process the data. Take a specific application for example. NSURLConnection network data requests are asynchronous by default. The implementation principle is to add them as event sources to the current RunLoop after creation, the process of waiting for network response and network data acceptance is completed in a newly created independent thread, when this thread processes a certain stage, for example, after receiving the response from the other party or receiving network data, it notifies the previous thread to execute its related delegate method. Therefore, in Cocoa, we often see methods such as <CODE> scheduleInRunLoop: forMode: </CODE>. This is to add it to the event source. When an event is detected, the related delegate method is called. For the CoreFoundation layer, the common mode is to create an Input Source and add the input source to the RunLoop through the <CODE> CFRunLoopAddSource </CODE> function, the related callback function is called. For example, CFSocket usage. In addition, RunLoop also has a concept of running mode. Every running cycle must run in a certain mode, and the existence of the mode is to filter the event source and observer, only the event sources and observers that are consistent with the current RunLoop running mode will be activated.
Ii. Thread startup: After a thread is started, the thread enters any of the three States: running, ready, and blocked ). If a thread is not currently running, it is not blocked, it is waiting for external input, or it is ready to wait for CPU allocation. The thread continuously switches between the three States until it finally exits or enters the interrupted state.
Iii. Thread execution:
1. Thread Synchronization:
NSLock: A lock provides an effective protection mode for only one thread to execute code at a time. The most common lock is the mutex exclusive lock, which we usually call mutex ". When a thread tries to obtain a mutex lock that has been occupied by other threads, it will be blocked until other threads release the mutex lock.
NSCondition: conditions ensure the proper order of execution of your application tasks. A condition acts as a gatekeeper, blocking a given thread until it represents a true condition. In this case, the condition releases the thread and allows it to continue execution.
Atomic operations are another way to protect and synchronize data access. Atomic operations provide lightweight methods to replace locks in the following scenarios, where you can perform mathematical or logical operations on scalar data types. Atomic operations use special hardware facilities to ensure that variable changes are completed before other threads can access them.
4. Thread communication: Cocoa provides two methods for iOS thread communication,
One is performSelector.
[Html]
@ Interface NSObject (nsthread1_madditions)
-(Void) specified mselecw.mainthread :( SEL) aSelector withObject :( id) arg waitUntilDone :( BOOL) wait modes :( NSArray *) array;
-(Void) specified mselecw.mainthread :( SEL) aSelector withObject :( id) arg waitUntilDone :( BOOL) wait;
// Equivalent to the first method with kCFRunLoopCommonModes
-(Void) implements mselector :( SEL) aSelector onThread :( NSThread *) thr withObject :( id) arg waitUntilDone :( BOOL) wait modes :( NSArray *) array NS_AVAILABLE (10_5, 2_0 );
-(Void) implements mselector :( SEL) aSelector onThread :( NSThread *) thr withObject :( id) arg waitUntilDone :( BOOL) wait NS_AVAILABLE (10_5, 2_0 );
// Equivalent to the first method with kCFRunLoopCommonModes
...
@ End
The other is NSMachPort (NSMachPort is a chicken rib, and inter-thread communication should be done through javasmselector)
5. Exit of Thread
You can use the delegate method of applicationShouldTerminate: to delay the interruption of the program until a period of time or cancel the program. When delayed interruption occurs, your program needs to wait until the threads in any cycle have completed their tasks and called the replyToApplicationShouldTerminate: method. For more information about these methods, see NSApplication Class Reference.
6. Handling exceptions
1. In Cocoa, an NSException object is a self-contained object. Once it is triggered, it can be passed from one thread to another.
2. In some cases, exception handling may be automatically created. For example, @ synchronized in Objective-C contains an implicit exception handling.
3. If a thrown exception fails to be captured in the auxiliary thread, your main thread also fails to catch the exception: the process to which it belongs will be interrupted.
4. If you need to notify another thread (such as the main thread) of a special situation in the current thread, you should capture the exception and simply send the message to other threads to tell what happened.
5. the thread that causes the exception can continue to execute (if possible), wait for the instruction, or simply exit.