I have an app that needs to send collected data every X milliseconds (and NOT sooner!). My first thought was to stack up the data on an NSMutableArray (array1) on thread1. When thread2 has finished waiting it’s X milliseconds, it will swap out the NSMutableArray with a fresh one (array2) and then process its contents. However, I don’t want thread1 to further modify array1 once thread2 has it.
This will probably work, but thread safety is not a field where you want to “just try it out.” What are the pitfalls to this approach, and what should I do instead?
(Also, if thread2 is actually an NSTimer instance, how does the problem/answer change? Would it all happen on one thread [which would be fine for me, since the processing takes a tiny fraction of a millisecond]?).
The pitfalls of this approach have to do with when you “swap out” the
NSArrayfor a fresh one. Imagine that thread1 gets a reference to the array, and at the same time thread2 swaps the arrays and finishes processing. Thread1 is now writing to a dead array (one that will no longer be processed), even if it’s just for a few milliseconds. The way to prevent this, of couse, is by using synchronized code-blocks (i.e., make your code “thread-safe”) in the critical sections, but it’s kind of hard not to overshoot the mark and synchronize too much of your code (sacrificing performance).So the risks are you’ll:
The idea is to “migrate away from threads” which is what this link is about.