Objective-C 中的无锁消息队列
我的 iOS 应用程序需要将数据从图形线程发送到音频线程。这些数据包(代表要合成的声音)需要存储起来,直到音频线程准备好对它们进行操作。最明显要使用的数据结构是一个队列,其中图形线程推入队列头部,音频线程从队列尾部拉出。音频线程实时运行,任何锁定都可能导致声音故障。有没有一种线程安全的方法可以在没有锁的情况下做到这一点?
我已经尝试过 PerformSelector:onThread:withObject:waitUntilDone 但没有运气。我认为这是因为音频线程没有关联的运行循环。
在我看来,我可以在这里构建类似基于 ac 数组的环形缓冲区之类的东西,它将保存指向我的消息的指针,其中生产者线程将负责移动写入头,而消费者线程将负责移动写入头。读头。我怎样才能确保这样的事情实际上是线程安全的? 关于非阻塞算法的维基百科提到无锁环形缓冲区可以在不使用低级的情况下实现(汇编)代码,但我对自己对线程如何共享机器控制的理解没有足够的信心,无法确保我正在实现的实际上是线程安全的。
My iOS app needs to send data from a graphics thread to an audio thread. These data bundles (representing sounds to be synthesized) need to be stored until the audio thread is ready to act on them. The obvious data structure to use is a queue where the graphics thread pushes to the head, and the audio thread pulls from the tail. The audio thread is running in real-time, and any locks are likely to result in audible glitches. Is there a thread-safe way to do this without locks?
I already tried performSelector:onThread:withObject:waitUntilDone with no luck. I think this is because the audio thread has no associated run loop.
It seems to me I could build something like a c array-based ring buffer here, which would hold pointers to my messages, where the producer thread would be in charge of moving the write head, and the consumer thread would be in charge of moving the read head. How can I ensure that such a thing is actually thread-safe? The wikipedia on non-blocking algorithms mentions lockless ring buffers as being implementable without using low-level (assembly) code, but I'm not confident enough in my own understanding of how threads share control of the machine to be sure that what I'm implementing is in fact thread-safe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来像是 NSOperationQueue 的工作。
请阅读 Apple 的并发编程指南以开始使用。
Sounds like a job for
NSOperationQueue
.Read Apple's Concurrency Programming Guide to get started.
时间限制并不像您想象的那么重要。你有足够的时间(在合理的范围内)来提供缓冲。
我建议你先实现一个常规的锁定队列。这可能不会成为问题。如果是的话,锁定可能不会成为瓶颈。我已经完成了大量的音频工作,包括使用锁毫无问题地实现您想要做的事情的许多变体。
也就是说,我确信有一种方法可以使用 OSAtomic.h。这是一篇很好的博客文章< /a> 就可以了。
The time constraint is not as critical as you think. You have plenty of time (within reason) to provide buffers.
I suggest you just implement a regular locking queue first. It probably won't be an issue. And if it is, it probably won't be the locking that will be the bottleneck. I've done tons of audio stuff including implementing many variations of exactly what you want to do with no problems using locks.
That said, I'm sure there is a way to implement a lockless thread-safe queue using the primitives in OSAtomic.h. Here is a good blog post on it.