Graphics Reference
In-Depth Information
If your application is accessing a prop-
erty on its main thread and that same
property gets accessed on a background
thread at the same time, the results are
undefined. It is possible that the change
will not go through or that it could
cause a crash deep within the Core
Animation API or any other result.
When you try to fetch a property and
change it and then restore the property
to its previous state, those actions
should be wrapped in a lock to make
them atomic, as shown in Listing 12-6.
NOTE
What Does Atomic Mean?
Atomic is defined as consisting of a set of
operations that can be combined so that
they appear to the rest of the system to be a
single operation with only two possible
outcomes: success or failure.
LISTING 12-6
Locking Layer Changes
[layer lock]
float opacity = layer.opacity;
layer.opacity = opacity + .1;
[layer unlock];
In this example, a [CATransaction lock] is requested to prevent any other thread from
obtaining the same lock, effectively blocking the other threads. This serializes access to
the layer and its properties and guarantees that the accessed property won't change before
you are done with it.
Care should be taken when working with layers on multiple threads for a couple reasons:
.
Holding a lock too long can cause the user interface to stop drawing. Because access
to that layer is blocked, you cannot access it on another thread, and other parts of
the system also cannot access it until the lock is released. Remember, any time you
lock a layer, you need to unlock it as quickly as possible.
.
The second issue, which is inherit to all threading locks and not just Core
Animation, is the contempt of circular locks . If you lock a layer with a thread and
that layer needs access to another
property locked by another thread
waiting for access to the lock, that
can cause the entire application to
become unresponsive to user inter-
action, resulting in the eventual
crash of that application.
NOTE
What Is a Circular Lock?
A circular lock (or deadlock) is a situation
wherein two or more competing threads are
waiting for the other to finish, and thus
neither ever does. This is illustrated in
Figure 12-6.
 
Search WWH ::




Custom Search