NSThread 获取队列并处理它
我有一个应用程序需要每 X 毫秒发送一次收集的数据(而且不能更快!)。我的第一个想法是将数据堆叠在 thread1
上的 NSMutableArray
(array1
) 上。当 thread2 完成等待 X 毫秒后,它将用新的 NSMutableArray (array2
) 交换 NSMutableArray,然后处理其内容。但是,一旦 thread2
拥有 array1
,我不希望 thread1
进一步修改它。
这可能会起作用,但线程安全并不是您想要“尝试一下”的领域。这种方法有哪些陷阱,我应该做什么?
(另外,如果 thread2
实际上是一个 NSTimer 实例,问题/答案会如何变化?这一切都会发生在一个线程上吗[这对我来说很好,因为处理只需要一小部分时间)毫秒]?)。
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]?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 NSOperationQueue 或 Grand Central Dispatch。基本上,您将创建一个操作来接收数据并在 X 毫秒过去后上传数据。每个操作都是独立的,您可以配置队列,允许多少个并发操作、操作优先级等。
有关并发的 Apple 文档应该有所帮助:
http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
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
这种方法的缺陷与您将 NSArray“替换”为新的 NSArray 时有关。想象一下,线程 1 获取了对数组的引用,同时线程 2 交换了数组并完成处理。 Thread1 现在正在写入一个死数组(将不再被处理的数组),即使只是几毫秒。当然,防止这种情况的方法是在关键部分使用同步代码块(即,使代码“线程安全”),但是很难不超出标记并同步太多代码(牺牲性能)。
因此,您将面临以下风险:
这个想法是“从线程迁移”,这就是 此链接是关于。
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 (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.