J.Doe
J.Doe

Reputation: 1552

iOS memory shared between CPU and GPU and what that means for reading

I have a MTLBuffer that is using memory that is allocated by the cpu and thus shared by both the cpu and the GPU.

Per Apple's suggestion I am using triple buffering to remove latency that might be caused by one processor waiting on the other to finish.

My vertex data changes every frame so every frame I am writing to one section of the array with the CPU and reading a different section with the GPU.

What I would like to do is read some of the values that the GPU is currently also reading as they save me some time doing calculations for the section of the buffer the CPU is writing to.

Essentially this is because the current frame's data is dependent on the previous frames data.

Is this valid? Can the CPU and the GPU be reading from the same portion of memory at once since memory is shared on iOS?

Upvotes: 4

Views: 1471

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90681

I think that's valid and safe, for two reasons. First, CPUs actually often have to read in order to write. Things like caches and memory buses don't allow for access to RAM at the granularity we usually think of (byte or even register size). In order to write, it usually has to read a larger chunk from memory, modify just the part written, and then (eventually) write the larger chunk back to memory. So, even the approach where you don't explicitly read from parts of the buffer that the GPU is reading and you only write to parts that the GPU isn't accessing can, in theory, still be implicitly reading from parts of the buffer that the GPU is reading. Since we're not given the info we'd need to reliably avoid that, I'd say it isn't considered a problem.

Second, no warning is given about what you describe in Apple's docs. There's the "Maintaining Coherency Between CPU and GPU Memory" section in the article about resource objects. That only discussed the case where either the CPU or GPU are modifying shared data, not where both are just reading.

Then there's the "Resource Storage Modes and Device Memory Models" section describing the new storage modes introduced with iOS 9 and macOS 10.11. And the docs for MTLResourceStorageModeShared itself. Again, there's mention of reading vs. writing, but none about reading vs. reading.

If there were a problem with simultaneous reading, I think Apple would have discussed it.

Upvotes: 4

Related Questions