开发者

lockless message queue in Objective-C

开发者 https://www.devze.com 2023-02-20 04:30 出处:网络
My iOS app needs to send data f开发者_JS百科rom 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 ac

My iOS app needs to send data f开发者_JS百科rom 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.


Sounds like a job for NSOperationQueue.

Read Apple's Concurrency Programming Guide to get started.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号