[英]NSThread Picks Up Queue and Processes It
I have an app that needs to send collected data every X milliseconds (and NOT sooner!). 我有一个应用程序需要每X毫秒(而不是更快!)发送收集的数据。 My first thought was to stack up the data on an NSMutableArray
( array1
) on thread1
. 我的第一个想法是将数据堆积在thread1
的NSMutableArray
( array1
)上。 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. 当thread2
等待X毫秒完成时,它将用一个新的( array2
)换出NSMutableArray,然后处理其内容。 However, I don't want thread1
to further modify array1
once thread2
has it. 但是,我不希望thread1
一旦thread2
拥有它就进一步修改array1
。
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]?). (此外,如果thread2
实际上是一个NSTimer实例,问题/答案如何改变?这是否都将在一个线程上发生(对我来说很好,因为处理只需要一毫秒的时间)?)。
You should use either NSOperationQueue or Grand Central Dispatch. 您应该使用NSOperationQueue或Grand Central Dispatch。 Basically, you'll create an operation that receives your data and uploads it when X milliseconds have passed. 基本上,您将创建一个接收数据并在X毫秒过去后上传数据的操作。 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: Apple关于并发的文档应该可以帮助您:
http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html 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. 当您“交换” NSArray
以获得新的方法时,这种方法的陷阱就产生了。 Imagine that thread1 gets a reference to the array, and at the same time thread2 swaps the arrays and finishes processing . 想象一下thread1获得了对数组的引用,同时thread2交换了数组并完成了处理 。 Thread1 is now writing to a dead array (one that will no longer be processed), even if it's just for a few milliseconds. Thread1现在正在写入一个失效数组(将不再处理该数组),即使只是几毫秒。 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: 因此,风险是:
The idea is to "migrate away from threads" which is what this link is about. 这个想法是“从线程迁移”,这就是链接的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.