Thread Safety in Core Foundation

Core Foundation is thread-safe to a large degree. That is, it is sufficiently thread-safe that, if you program with care, you should not run into any problems related to competing threads. It is notably thread-safe in the common cases, such as when you query, retain, release, and pass around immutable objects. Even central shared services that might be queried from more than one thread are reliably thread-safe. One example of such shared services is Core Foundation Preference Services.

Where Core Foundation is not thread-safe is in the lower-level cases involving mutations to objects. One reason for this is performance, which is critical in lower-level cases. Moreover, it is usually not possible to achieve absolute thread safety at this level. You cannot rule out, for example, indeterminate behavior resulting from retaining an object obtained from a collection. The collection itself might be freed before the call to retain is made.

In those cases where Core Foundation objects are to be accessed from multiple threads and mutated, your code should protect against simultaneous access by using locks at the access points. For instance, the code that enumerates the objects of a Core Foundation array should protect against someone else mutating the array by making the appropriate locking calls around the enumerating block. Or, instead of locks, your code could use some higher-level protocol or synchronization to ensure thread safety.


© 1999 Apple Computer, Inc. – (Last Updated 07 September 99)