iOS multithreaded Development (ii)---Thread management

Source: Internet
Author: User

Thread Management

Thread management consists of creating, configuring, and exiting three parts. This includes the cost of creating threads, thread creation, thread property configuration, thread principal entry function writing, thread interruption, etc., thread creation cost 1, stack space allocated for worker threads, ease of system and process management, and allocation of space A for function parameters and local variables, kernel data structures (kernel Data structures)---approximately 1kb,this memory is used to store the thread data structures and attributes, much of which are allocate D as wired memory and therefore cannot be B, stack space (stack spaces)---512 KB (Secondary threads)/8 MB (Mac OS X main thre AD)/1 MB (IOS main thread), the minimum allowed stack size for secondary threads are KB and the stack size must be a mul Tiple of 4 KB. The space for this memory was set aside in your process space at thread creation time, but the actual pages associated with That memory is not created until they is need 2, the time cost to create the thread--approximately 90ms, the creation time depends on the processor load, the calculation speed, and the available system and program space I Second, create threads         creating threads requires three parts of the work: the principal entry point, the available thread (to start the thread being created), the thread's property configuration. There are many ways to create threads, such as Nsthread,posix,nsobject, and other methods (multiprocessing Services)       1, using Nsthread to create threads         a,[nsthread detachnewthreadselector: @selector (mythreadmainmethod:) totarget:self withobject:nil];          The principal entry point of a thread is Mythreadmainmethod, and the available thread is a self-existing thread, but the properties of this thread cannot be configured before threads are created. Can only be configured in thread         b, create a new Nsthread instance, and then call his start method to start the thread               Nsthread  *mythread = [[Nsthread alloc] initwithtarget:self selector: @selector (Mythreadmainmethod) withobject:nil];              [MyThread start]; //actually create the THREAD&NBSP ;         Thread principal entry is Mythreadmainmethod, the available thread is a self-existing thread, thread properties can be set before the Start method call after a new Nsthread instance is created   Note: Threads created through Nsthread are one of the most convenient ways to communicate between threads through the PerformSelector:onThread:withObject:withUntilDone method.     &NBSP;&NBSP;2,Use POSIX to create threads         a,creating A thread in C #include <assert.h>#include <pthread.h> void* posixthreadmainroutine (void* data){//Do Some     ......return NULL}  void Launchthread (){//Create the thread using POSIX routines.

pthread_attr_t attr;

pthread_t Posixthreadid;int returnval;   returnval = Pthread_attr_init (&attr);assert (!returnval); returnval = pthread_attr_setdetachstate (&attr, pthread_create_detached); assert (!returnval);int threaderror = Pthread_create (&posixthreadid, &attr, &posixthreadmainroutine, NULL);returnval = Pthread_attr_destroy (&attr);assert (!returnval);if (threaderror! = 0) {//Report an error. }}in the above code, the thread principal entry point is Posixthreadmainroutine, which creates the thread through Pthread_create, initializes and configures the thread properties before the thread is created pthread_attr_init/pthread_attr _setdetachstateNote:C-based applications, common inter-thread communication includes using ports (ports), conditions (conditions), and shared memory 3, creating threads using NSObject [myObj performselectorinbackground: @selector (dosomething) Withobject:nil]; To create a thread by referencing the Nsthread method4, creating threads with other technologiesthe only thing to consider is the multi-processing service (multiprocessing services), which is itself executing on a POSIX thread5, use POSIX thread in Cocoa program, need to pay attention to the problem of A,cocoa framework protection for multithreaded applications, the cocoa framework uses locks and other synchronization methods to ensure correct use of the code. But to avoid the loss of performance caused by these locks, the cocoa framework creates these locks only when the application creates the Nsthread class to generate its first new thread. If you create a new thread with POSIX only, the cocoa framework will not automatically create these locks that protect the synchronization. This could cause cocoa to collapse.Workaround: Use the Nsthread class to generate a thread and let him exit immediately before creating the first new thread. This ensures that the locks needed for the cocoa frame are in place. B, a combination of POSIX and cocoa locksyou can mix posix and cocoa locks in the same application, because cocoa locks and conditional objects are basically just encapsulating POSIX mutexes and conditions. But the two cannot be cross-used, and Cocoa's nslock invokes the POSIX-created mutex object, which is stillThird, configure thread propertiesthread properties mainly include the thread's stack size, local storage, thread's detachment state (detached), Thread priority1, configure the thread's stack sizeA,cocoa thread, only threads created through the new Nsthread class can configure the thread's stack size [MyThread setstacksize]; b,posix thread, creating a limited pthread_attr_t data structure, using the pthread_attr_setstacksize function to set the thread stack size2, configure thread local storage----each thread maintains a key-value dictionary structure, how to set and access this structure?A,cocoa thread, nsmutabledictionary *mdict = [[Nsthread CurrentThread] threaddictionary];b,posix Thread, set this structure through pthread_setspecific, access this structure through pthread_getspicific3, set the detachment state of the threadDetach Thread---when the thread finishes, the system automatically frees the memory space it occupiescan connect thread (joinable thread)---------------------- When an application exits, the disengagement thread can be interrupted immediately, while the thread that can connect is not. Each connected thread must be connected when the process is allowed to exit. So when a thread is working periodically and not allowed to be interrupted, such as saving data to a hard disk, a thread that can be connected is the best choice . If you want to create a threaded connection, the only way to do this is to use a POSIX thread. POSIX threads created by default are available for connection. Set whether to detach from a property by using the Pthread_attr_setdetachstate function4, Thread priorityA,cocoa thread, [Nsthread setthreadpriority]; set Thread priorityb,posix Thread, Pthread_setschedparam function implementation priority settingNote: When high and low threads interact, be aware of the congestion caused by low-thread starvation, resulting in performance bottlenecks that affect application performance. Four, thread principal entry functionthe main entrance function of the thread is to do three work:1, create an auto-release pool (autorelease), note: To actively clean up the memory inside the pool automatically, increase the memory space of the thread2, set exception handlingAdd the Try/catch module, catch any unknown exceptions, and provide the appropriate response3, set up a run loopfor threads that require dynamic processing of incoming task requests, you need to add a run loop to the threadFive, Middle thread breakin the interrupt thread, it is important to ensure that the thread exits from the main entry function to ensure that the thread's resources are automatically freed. -(void) Threadmainroutine{Bool Moreworktodo = YES;Bool exitnow = NO;nsrunloop *runloop = [Nsrunloop currentrunloop]; //Add the Exitnow BOOL to the thread dictionarynsmutabledictionary *threaddict = [[Nsthread CurrentThread] threaddictionary];[threaddict setvalue:[nsnumber Numberwithbool:exitnow] forkey:@ "Threadshouldexitnow"]; //Install an input method[self myinstallcustominputsource]; While (Moreworktodo &&!exitnow) {//Do one chunk of a larger body of work here// Change the value of the Moreworktodo a Boolean when done//Run the run loop but timeout immediately if the input source isn ' t waiting to fire[Runloop rununtildonedate:[nsdate Date]];//Check the see if an input source handle changed the Exitnow value.Exitnow = [[Threaddict valueforkey:@ "Threadshouldexitnow"] boolvalue]; }}

iOS multithreaded Development (ii)---Thread management

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.