re: psychotik's suggestion: volatile
is a keyword in C that basically tells the compiler to avoid optimizing usage of the symbol it's attached to. This is important for multithreaded code, or code that directly interfaces with hardware. However, it's not very useful for working with blocks of memory (from malloc()
or NSData
.) As psychotik said, it's for use with primitives such as an int
or a pointer (i.e. the pointer itself, not the data it points to.) It's not going to make your data access any faster, and may in fact slow it down by defeating the compiler's optimization tricks.
For cross-thread synchronization, your fastest bet is, I think, an OSSpinLock
if you don't need recursive access, or a pthread_mutex
set up as recursive if you do. Keep in mind OSSpinLock
is, as the name suggests, a spin lock, so certain usage patterns make it less efficient than a pthread_mutex
, but it's also extremely close to the metal (it's based off the hardware's atomic get/set operations.)
If your data really is being accessed frequently enough that you're concerned with locking performance, you'll probably want to avoid NSData
and just work with a block of memory from malloc()
--but, without knowing more about what you're trying to accomplish or how frequently you're accessing the data, a solution does not readily present itself. Can you tell us more about your intent?