Suppose a Metal vertex shader A
updates a buffer buf
. Also suppose I have a second vertex shader B
that is encoded after A
. Can B
use the results in buf
or is it possible that B
will begin executing before A
has finished, meaning the contents of the buffer are not ready?
The second vertex shader B
is free to execute before vertex shader A
if they encoded in the same MTLRenderCommandEncoder
. If you'd like to read the output of A
in B
, then they must be encoded by separate MTLRenderCommandEncoder
's.
Note, however, the same is not true of compute dispatches within a MTLComputeCommandEncoder
. The relevant part of the doc states:
Executing a Compute Command
To encode a command to execute a compute function, call the dispatchThreadgroups:threadsPerThreadgroup: method of MTLComputeCommandEncoder and specify the threadgroup dimensions and the number of threadgroups. You can query the threadExecutionWidth and maxTotalThreadsPerThreadgroup properties of MTLComputePipelineState to optimize the execution of the compute function on this device.
For most efficient execution of the compute function, set the total number of threads specified by the threadsPerThreadgroup argument to the dispatchThreadgroups:threadsPerThreadgroup: method to a multiple of threadExecutionWidth. The total number of threads in a threadgroup is the product of the components of threadsPerThreadgroup: threadsPerThreadgroup.width * threadsPerThreadgroup.height * threadsPerThreadgroup.depth. The maxTotalThreadsPerThreadgroup property specifies the maximum number of threads that can be in a single threadgroup to execute this compute function on the device.
Compute commands are executed in the order in which they are encoded into the command buffer. A compute command finishes execution when all threadgroups associated with the command finish execution and all results are written to memory. Because of this sequencing, the results of a compute command are available to any commands encoded after it in the command buffer.
To end encoding commands for a compute command encoder, call the endEncoding method of MTLComputeCommandEncoder. After ending the previous command encoder, you can create a new command encoder of any type to encode additional commands into the command buffer.