iOS multithreaded Programming Guide (appendix)

Source: Internet
Author: User
Tags data structures documentation mutex posix thread class

This appendix describes some of the key advanced thread security frameworks for Mac OS X and iOS. The information in this appendix may be changed. Cocoa

The guidelines for using multithreading on cocoa include the following: Immutable objects are generally thread-safe. Once you create them, you can transfer these objects securely between threads. On the other hand, mutable objects are usually not thread-safe. In order to use mutable objects in multi-threaded applications, the application must be properly synchronized. For more information, see "Variable and immutable contrasts." Many objects that are unsafe to use in multithreading are considered "thread insecure." As long as there is only one thread at a time, many of these objects can be used by multiple threads. This type of object, called the main thread that specifically restricts the application, is typically called this way. The main thread of the application is responsible for handling events. Although the application kit will continue to work while other threads are included in the event path, the operation may be disrupted sequentially. If you want to use a thread to paint a view, put all the drawing code in the middle of the NSView Lockfocusifcandraw and Unlockfocus methods.

In order to use POSIX threads inside cocoa, you must first turn cocoa into multithreaded mode. For more information, see the "using POSIX threads in Cocoa Applications" section. thread safety for the underlying framework (Fondation Framework)

There is a misconception that the underlying framework (Foundation framework) is thread-safe and that the application kit is not thread-safe. Unfortunately, this is a general generalization, resulting in a little misleading. Each frame contains a thread-safe part and a non-thread-safe section. The following sections describe the thread-safe parts of the foundation framework.

thread-safe classes and functions

The following classes and functions are generally considered thread-safe. You can use one of their instances in multiple threads without having to acquire a lock. Nsarray nsassertionhandler nsattributedstring nscalendardate nscharacterset nsconditionlock NSConnection NSData NSDate Nsdecimal functions Nsdecimalnumber Nsdecimalnumberhandler nsdeserializer nsdictionary Nsdistributedlock nsdistributednotificationcenter nsexception Nsfilemanager (in Mac OS X v10.5 and later) NSHost NSLock NS LOG/NSLOGV nsmethodsignature nsnotification nsnotificationcenter nsnumber nsobject NSPortCoder NSPortMessage Nsportnameserver nsprotocolchecker nsproxy nsrecursivelock nsset nsstring nsthread NSTimer NSTimeZone NSUserDefaults Nsvalue also has allocation and retain functions zone and memory functions of objects

non-thread-safe classes

The following classes and functions are generally considered to be thread-safe. In most cases, you can use these classes in any thread, as long as you use them in only one thread at a time. Refer to the documentation for additional details for these classes. Nsarchiver nsautoreleasepool nsbundle nscalendar nscoder nscountedset nsdateformatter NSEnumerator NSFileHandle Nsformatter nshashtable functions nsinvocation nsjavasetup functions nsmaptable functions NSMutableArray Nsmutableattributedstring nsmutablecharacterset nsmutabledata nsmutabledictionary NSMutableSet NSMutableString Nsnotificationqueue nsnumberformatter nspipe nsport nsprocessinfo nsrunloop nsscanner NSSerializer NSTask NSUnarchiver Nsundomanager User name and home directory functions

Note that although the Nsserializer,nsarchiver,nscoder and Nsenumerator objects themselves are thread-safe, they are placed here because it is not safe to change the object data when their encapsulated objects are used. For example, in the case of archiving, it is not safe to modify the archived objects. For an enumeration, it is unsafe for any thread to modify the collection of enumerations.

classes that can only be used for the main thread

The following classes must be used only in the main thread class of the application. Nsapplescript

Variable vs immutable

Immutable objects are usually thread-safe. Once you create them, you can transfer them securely between threads. Currently, when using immutable objects, you should also remember to use reference counting correctly. If you do not properly release an object that you have no reference to, you may subsequently cause an exception.

mutable objects are usually not thread-safe. To use mutable objects in multithreaded applications, applications should use locks to synchronize access to them (for more information, see the "Atomic Operations" section). Typically, a collection class (for example, nsmutablearray,nsmutabledictionary) is considered variable when it is non thread safe. This means that if one or more threads change an array at the same time, the problem occurs. You should surround them with locks by thread reading and writing them.

Even if a method requires the return of an immutable object, you should not simply assume that the returned object is immutable. Depending on the implementation of the method, the returned object may be mutable or immutable. For example, a return type is a nsstring method that may actually return a nsmutablestring due to its implementation. If you want to make sure that the object is immutable, you should use an immutable copy.

 

can be reentrant

Reentrant is the possibility of "invoking" other operations on the same object or on a different object. Keeping and releasing objects is an example of a "call" that is likely to be overlooked.

The following list lists the partially explicit reentrant objects of the foundation framework. All other classes may or may not be reentrant, or they might be reentrant in the future. A complete analysis of the reentrant is impossible, and the list will be endless. Distributed Objects nsconditionlock nsdistributedlock nslock nslog/nslogv nsnotificationcenter NSRecursiveLock Nsrunloop Nsuserdefaults

initialization of a class

The OBJECTIVE-C runtime system sends a initialize message to the class before it receives any other messages. This gives the class the opportunity to set its run-time environment before it is used. In a multithreaded application, the runtime guarantees that only one thread (the thread that sends the first message to the class) executes the initialized method, and the second thread blocks until the Initialize method of the first thread finishes execution. During this time, the first thread can continue to invoke methods on other classes. The Initialize method should not depend on the second thread's invocation of this class. If this is not the case, two threads will cause a deadlock.

 

Automatic release pool (autorelease pools)

Each thread maintains its own NSAutoreleasePool stack object. Cocoa wants to have an available automatic free pool within each current thread's stack. If an automatic free-release pool is unavailable, the object will not be released, causing a memory leak. For the main thread of application kit, it usually automatically creates and consumes an automatic release pool, but the worker thread (and other only foundationd programs) must be created manually before using cocoa. If your thread is running for long periods of time, it is possible to potentially generate many objects that are automatically released, and you should periodically destroy them and create an automatic release pool (just as application kit does with the main thread). Otherwise, automatic release of objects will accumulate and cause memory footprint. If your detach thread does not use cocoa, you do not need to create an automatic release pool.

Run Loops

Each thread has one or more run loop. However, each run loop and each thread has its own input pattern that determines the release of the run loop to listen for those input sources. The input pattern is defined on a run loop and does not affect the input modes defined in the other run loop, even if they have the same name.

If your thread is based on application Kti, the run loop of the main thread runs automatically, but the worker threads (and only foundation applications) must start their run loop themselves. If a detach thread does not enter the run loop, the thread exits immediately after the method that completes them is executed.

Although the appearance may be thread-safe, the Nsrunloop class is not thread-safe. You can only invoke the method of its instance in the thread that owns them. thread safety for the application Kit framework

The following sections describe the thread safety of the application Kit framework.

 

non-thread-safe classes

The following classes and functions are usually not thread-safe. In most cases, you can use these classes on any thread, as long as you have only one thread at a time to use them. View the documentation for these classes for more details. Nsgraphicscontext. For more information, see "Nsgraphicscontext restrictions." Nsimage. For more information, see "Nsimage restrictions." Nsresponder. Nswindow and all of its subclasses. For more information, see "Window restrictions

classes that can only be used for the main thread

The following classes must be used only in the main thread of the application. Nscell and all of its subclasses. NSView and all of its subclasses. For more information, see "NSView restrictions."

Window Restrictions

You can create a window on the worker thread. Application kit ensures that window-related data structures are freed from the main thread to avoid conditions. In applications that contain a large number of Windows, window objects can leak.

You can also create modal windows on the worker thread. When the main thread runs modal loop, the application kit blocks calls from the worker thread.

Event-handling routine restrictions

The main thread of the application is responsible for handling events. The main thread blocks the NSApplication run method, which is usually included in the main function. When the application kit continues to work, if other threads are included in the event path, then the operation may be disrupted in order. For example, if two different threads are responsible for critical events, then critical events may not arrive in order. By having the main thread handle events, events can be assigned to worker threads to be processed by them.

You can use the NSApplication Postevent:atstart method in the worker thread to pass an event to the main thread's event queue. However, the order does not guarantee that the sequence of events entered by the user is the same. The application's main thread still assists in handling event queue events.

Painting Restrictions

Application kit is usually thread-safe when using its painting functions and classes, including the Nsbezierpath and NSString classes. For more information about using these classes, describe them in the following sections. Additional information and threads about painting can be viewed Cocoa Drawing Guide.

a) NSView restrictions

NSView are usually thread-safe and contain several exceptions. You should only perform the creation, destruction, resizing, moving, and other operations of the NSView in the main thread of the application. It is also thread-safe in other worker threads as long as you place the drawing code between the Lockfocusifcandraw and the Unlockfocus methods.

If the application worker thread wants to tell the main thread to redraw the view, it must not invoke Display,setneedsdisplay:,setneedsdisplayinrect:, or Setviewsneeddisplay: method directly on the worker thread. Instead, you should give the main thread a message to call these methods, or use the PerformSelectorOnMainThread:withObject:waitUntilDone: method.

The graphical state of the system view (Gstates) is based on the different threads of each thread. Using graphic state can get better painting performance in single-threaded applications, but this is not the case now. Improper use of graphic State may cause the main thread's drawing code to be less efficient.

b) Nsgraphicscontext restrictions

The Nsgraphicscontext class represents the painting context, which is provided by the underlying painting system. Each Nsgraphicscontext instance has its own painting state: coordinate system, cropping, current font, and so on. An instance of this class automatically creates its own Nswindow instance on the main thread. If you perform a painting operation on any worker thread, you need to create a new Nsgraphicscontext instance for that thread.

If you perform painting on any worker thread, you must manually refresh the drawing call. Cocoa does not automatically update the contents of the worker thread painting, so you need to call the Nsgraphicscontext Flusgrahics method when you finish painting. If your application is only in the main thread painting, you do not need to refresh the painting calls.

c) Nsimage restrictions

A thread can create a Nsimage object, paint it into a picture buffer, and pass it to the main thread to paint. The underlying picture cache is shared by all threads. For more information about pictures and how to cache, see Ccocoa Drawing Guide. Core Data Framework

The Core data framework usually supports multithreading, although some considerations for usage need to be noted. For more information on these considerations, see the "Multi-threading with Core Data" section of Core Data programing guide. Core Foundation (Central framework)

Core Foundation is thread-safe enough, and if your program is aware of it, you should not encounter any problem with threading competition. Typically, it's thread-safe, such as when you query, reference (retain), release, and pass immutable objects. It is also thread-safe to query central shared objects across multiple threads.

Like Cocoa, the Core Foundation is not thread-safe when it comes to objects or when their content is mutated. For example, as you would expect, it is not thread-safe to modify a variable data or variable group object or to modify an object in a mutable array. One of the reasons is performance, which is the key in this case. In addition, it is almost impossible to achieve full thread safety at this level. For example, you cannot exclude an indeterminate result from referencing (retain) an object from a collection. The collection itself may have been released before being invoked to refer to (retain) the objects it contains.

In these cases, when your object is accessed or modified by multiple threads, your code should use a lock in place to protect them from simultaneous access. For example, the code that enumerates the core Foundation array objects should use appropriate locks around the enumeration block code to protect it from other thread modifications.

Terminology List

Application (Application)

A specific style program that displays a graphical user interface to the user.

condition (condition)

A structure used to synchronize resource access. The thread waits for a condition to determine whether it is allowed to continue running until the other line Cheng the condition to send a signal.

Critical Area (critical section)

Code that can only be executed by one thread at a time.

input sources (inputs source)

An asynchronous event source for a thread. The input source can be either port based or manually triggered and must be attached to the run loop of a thread.

thread that can be connected (join thread)

The thread that the resource will not be reclaimed immediately when exiting. A thread that can be connected must be explicitly detached or connected by another thread before the resource is reclaimed. A connecting thread provides a return value to the thread that connects it.

main thread (main thread)

A specific type of thread that is created together when the process is created. When the main thread of the program exits, the program exits.

Mutual Exclusion Locks (mutexes)

A lock that provides mutually exclusive access to a shared resource. A mutex can only be owned by one thread at a time. Attempting to acquire a mutex that is already owned by another thread puts the current thread in hibernation knowing that the lock is freed by another thread and is available to the current thread.

Action Object (Operation object)

An instance of the Nsoperation class. An action object encapsulates the code and data associated with a task into an execution unit.

Action Queue (Operation queue)

An instance of the Nsoperationqueue class. The operation queue manages the execution of the action object.

processes (process)

The Run-time instance of the application or program. A process has a separate memory space and system resources (including port permissions) that are assigned to other programs. A process always contains at least one thread (that is, the primary thread) and any number of extra threads.

programs (program)

A combination of code and resources that you can use to perform certain tasks. Programs do not require a graphical user interface, although graphical applications are also called programs.

recursive locks (recursive lock)

A lock that can be locked multiple times with the same thread.

Run Loop (running loop)

An event-handling loop in which events are received and assigned to the appropriate processing routines.

Run loop model (run loop mode)

A collection of input sources, timing sources, and run loop observers associated with a particular name. When running under a specific "mode", a run loop monitors the source and observer associated with the pattern.

Run Loop objects (run Loop object)

Nsrunloop class or Cfrunloopref an instance of an opaque type. These objects provide an interface within the thread that implements the event-handling loop.

Run loop Observer (run Loop observer)

The object that receives the notification when the run loop runs at different stages.

signal Volume (semaphore)

A protected variable that restricts access to shared resources. Mutual-exclusion locks (mutexes) and conditions (conditions) are different types of semaphores.

Tasks (Task)

The number of jobs to perform. Although some techniques (most notably Carbon-carbon multiprocessing services) Use the term in different ways, the most common usage is the abstract concept of the number of work that needs to be performed.

threads (thread)

An execution process flow inside the process. Each thread has its own stack space, but in addition to other threads of the same process sharing memory.

Timing Sources (timer source)

Is the source of the thread synchronization event. The timer produces one or more recurring events that are scheduled to be executed.


Concluding remarks

Multithreaded programming is very helpful when developing applications. For example, you can load pictures in the background, and so on after the picture is loaded and then in the main thread update, or in the background to handle some of the CPU to occupy a very long time of events (such as requesting the server, loading data, etc.). To realize the benefits of multithreaded programming, but also more combat, combined with a variety of multithreading technology. With special attention to the use of run loop, many developers rarely focus on the run loop when writing multithreaded applications. If you carefully read and master the details of the run loop, you will be able to write more graceful code. Synchronization is a commonplace of multithreaded programming, and it is estimated that everyone is familiar with the importance of synchronization in college.

Finally, this article in the translation process found that a lot of local literal translation into Chinese is more obscure, so the use of the way of transliteration, which inevitably caused some places may and the original text have certain discrepancies, so if you read the time to find any errors can send me an e-mail: Xyl.layne (a) gmail.com.

Finally, I can pay attention to micro-bo everyone to communicate and exchange learning.

Microblogging address: http://weibo.com/u/1826448972

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.