简体   繁体   中英

NSThread Picks Up Queue and Processes It

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]?).

You should use either NSOperationQueue or Grand Central Dispatch. Basically, you'll create an operation that receives your data and uploads it when X milliseconds have passed. Each operation will be independent and you can configure the queue wrt how many concurrent ops you allow, op priority, etc.

The Apple docs on concurrency should help:

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html

The pitfalls of this approach have to do with when you "swap out" the NSArray for 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 (ie, 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:

  • Make code that is not thread-safe
  • Make code that overuses synchronize and is slow (and threads already have a performance overhead)
  • Make some combination of these two: slow, unsafe code.

The idea is to "migrate away from threads" which is what this link is about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM