Here is a complete C++ and Metal program that uses a compute shader to multiply an array by a scalar:
cpp Copy code
#include <metal_stdlib>
using namespace metal;
kernel void multiplyByScalar(device float* array [[buffer(0)]],
constant float& scalar [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
array[index] *= scalar;
}
#include <Metal/Metal.h>
#include <iostream>
using namespace std;
int main() {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> commandQueue = [device newCommandQueue];
const int arraySize = 8;
float hostArray[arraySize] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0};
float scalar = 2.0;
id<MTLBuffer> arrayBuffer = [device newBufferWithBytes:hostArray
length:sizeof(hostArray)
options:MTLResourceStorageModeShared];
id<MTLBuffer> scalarBuffer = [device newBufferWithBytes:&scalar
length:sizeof(scalar)
options:MTLResourceStorageModeShared];
id<MTLComputePipelineState> pipelineState =
[device newComputePipelineStateWithFunction:multiplyByScalar];
id<MTLComputeCommandEncoder> commandEncoder =
[commandQueue commandBufferWithUnretainedReferences].computeCommandEncoder;
[commandEncoder setBuffer:arrayBuffer offset:0 atIndex:0];
[commandEncoder setBuffer:scalarBuffer offset:0 atIndex:1];
const int threadGroupSize = arraySize;
MTLSize threadsPerThreadgroup = MTLSizeMake(threadGroupSize, 1, 1);
[commandEncoder dispatchThreads:threadsPerThreadgroup
threadsPerGrid:MTLSizeMake(1, 1, 1)];
[commandEncoder endEncoding];
[commandEncoder.commandBuffer commit];
memcpy(hostArray, [arrayBuffer contents], sizeof(hostArray));
cout << "Result: ";
for (int i = 0; i < arraySize; i++) {
cout << hostArray[i] << " ";
}
cout << "\n";
return 0;
}
This defines a compute shader kernel that multiplies each element of the input array by the scalar value. It sets up the array and scalar as Metal buffers, creates a compute pipeline state, encodes the compute command, dispatches the threads, and copies back the result to verify the computation.