Dispatch a Vulkan compute shader
This guide compiles an eight-line GLSL compute shader to SPIR-V and dispatches it from a self-contained C11 Vulkan program to add 1 to every element of a 128-element unsigned integer buffer.
Because Vulkan treats compute queues as first-class citizens, this program opens no window, creates no swapchain, and never touches a fragment shader.
It runs the exact same computation as the WebGPU half of Draw a triangle and run a compute shader and the CUDA/HIP how-tos, explained conceptually in GPU compute.
Verify a Vulkan device and shader compiler
Check that a Vulkan physical device is visible and that glslangValidator is on PATH:
vulkaninfo --summary
glslangValidator --version
On Windows, both tools ship inside the LunarG Vulkan SDK.
On Linux, install your distribution’s vulkan-tools, libvulkan-dev (or equivalent headers), and glslang-tools / shaderc packages.
Even a CPU software implementation such as llvmpipe / lavapipe is enough to verify that your compilation and dispatch pipeline work end to end, though it will not measure hardware GPU throughput.
Compile the GLSL compute shader to SPIR-V
Save the shader as add_one.comp:
#version 450
layout(local_size_x = 64) in;
layout(std430, set = 0, binding = 0) buffer Data {
uint values[];
};
void main() {
uint i = gl_GlobalInvocationID.x;
if (i >= values.length()) return;
values[i] = values[i] + 1u;
}
Compile it ahead of time to SPIR-V binary bytecode:
glslangValidator -V add_one.comp -o add_one.spv
Unlike WebGPU — where Dawn or wgpu compiles WGSL source text at runtime — Vulkan’s vkCreateShaderModule expects precompiled SPIR-V bytecode (-V).
Write the C11 host program
Vulkan requires the host program to spell out every piece of setup explicitly:
-
Create a
VkInstance, enumerate physical devices, and locate a queue family advertisingVK_QUEUE_COMPUTE_BIT. -
Create a logical
VkDeviceand retrieve one queue from that compute family. -
Create a 128-element
VkBufferwithVK_BUFFER_USAGE_STORAGE_BUFFER_BIT, allocate host-visible and host-coherentVkDeviceMemory, bind them, and map the memory to write0, 1, …, 127. -
Load
add_one.spvinto aVkShaderModule, build a descriptor set layout and pipeline layout for one storage buffer, and create theVkPipeline. -
Allocate and update a descriptor set pointing at the storage buffer.
-
Record a command buffer that binds the pipeline and descriptor set, calls
vkCmdDispatch(cmd, 2, 1, 1)(2 workgroups of 64 lanes), and inserts aVkBufferMemoryBarrierfromVK_ACCESS_SHADER_WRITE_BITtoVK_ACCESS_HOST_READ_BITso the CPU can safely read the results. -
Submit the command buffer, wait for the queue to finish, verify the output, and destroy the objects in reverse order.
Save this program as add_one.c in the same directory as add_one.spv:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vulkan/vulkan.h>
#define CHECK(x) do { VkResult _r = (x); if (_r != VK_SUCCESS) { \
fprintf(stderr, "%s -> %d\n", #x, (int)_r); return 1; } } while (0)
static uint32_t* load_spv(const char* path, size_t* bytes) {
FILE* f = fopen(path, "rb");
if (!f) return NULL;
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
long len = ftell(f);
if (len <= 0 || (len % 4) != 0) { fclose(f); return NULL; }
*bytes = (size_t)len;
fseek(f, 0, SEEK_SET);
uint32_t* code = malloc(*bytes);
if (!code || fread(code, 1, *bytes, f) != *bytes) {
free(code);
fclose(f);
return NULL;
}
fclose(f);
return code;
}
int main(void) {
const uint32_t n = 128;
VkApplicationInfo app = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.apiVersion = VK_API_VERSION_1_2 };
VkInstanceCreateInfo ici = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pApplicationInfo = &app };
VkInstance instance;
CHECK(vkCreateInstance(&ici, NULL, &instance));
uint32_t ndev = 0;
CHECK(vkEnumeratePhysicalDevices(instance, &ndev, NULL));
if (!ndev) { fprintf(stderr, "no Vulkan device\n"); return 1; }
VkPhysicalDevice* devs = calloc(ndev, sizeof *devs);
CHECK(vkEnumeratePhysicalDevices(instance, &ndev, devs));
VkPhysicalDevice phys = devs[0];
free(devs);
uint32_t nq = 0, family = 0, found = 0;
vkGetPhysicalDeviceQueueFamilyProperties(phys, &nq, NULL);
VkQueueFamilyProperties* qf = calloc(nq, sizeof *qf);
vkGetPhysicalDeviceQueueFamilyProperties(phys, &nq, qf);
for (uint32_t i = 0; i < nq; i++) {
if (qf[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { family = i; found = 1; break; }
}
free(qf);
if (!found) { fprintf(stderr, "no compute queue\n"); return 1; }
float prio = 1.f;
VkDeviceQueueCreateInfo qci = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.queueFamilyIndex = family, .queueCount = 1, .pQueuePriorities = &prio };
VkDeviceCreateInfo dci = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.queueCreateInfoCount = 1, .pQueueCreateInfos = &qci };
VkDevice device;
CHECK(vkCreateDevice(phys, &dci, NULL, &device));
VkQueue queue;
vkGetDeviceQueue(device, family, 0, &queue);
VkBufferCreateInfo bci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = n * sizeof(uint32_t),
.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT };
VkBuffer buffer;
CHECK(vkCreateBuffer(device, &bci, NULL, &buffer));
VkMemoryRequirements req;
vkGetBufferMemoryRequirements(device, buffer, &req);
VkPhysicalDeviceMemoryProperties memp;
vkGetPhysicalDeviceMemoryProperties(phys, &memp);
uint32_t mt = UINT32_MAX;
const VkMemoryPropertyFlags wanted =
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
for (uint32_t i = 0; i < memp.memoryTypeCount; i++) {
if ((req.memoryTypeBits & (1u << i)) &&
(memp.memoryTypes[i].propertyFlags & wanted) == wanted) {
mt = i;
break;
}
}
if (mt == UINT32_MAX) { fprintf(stderr, "no host-visible coherent memory\n"); return 1; }
VkMemoryAllocateInfo mai = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.allocationSize = req.size, .memoryTypeIndex = mt };
VkDeviceMemory memory;
CHECK(vkAllocateMemory(device, &mai, NULL, &memory));
CHECK(vkBindBufferMemory(device, buffer, memory, 0));
uint32_t* mapped = NULL;
CHECK(vkMapMemory(device, memory, 0, req.size, 0, (void**)&mapped));
for (uint32_t i = 0; i < n; i++) mapped[i] = i;
size_t spv_bytes = 0;
uint32_t* spv = load_spv("add_one.spv", &spv_bytes);
if (!spv) { fprintf(stderr, "add_one.spv missing or invalid\n"); return 1; }
VkShaderModuleCreateInfo smi = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = spv_bytes, .pCode = spv };
VkShaderModule module;
CHECK(vkCreateShaderModule(device, &smi, NULL, &module));
free(spv);
VkDescriptorSetLayoutBinding binding = { .binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
.descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT };
VkDescriptorSetLayoutCreateInfo lci = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = 1, .pBindings = &binding };
VkDescriptorSetLayout set_layout;
CHECK(vkCreateDescriptorSetLayout(device, &lci, NULL, &set_layout));
VkPipelineLayoutCreateInfo plci = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 1, .pSetLayouts = &set_layout };
VkPipelineLayout pipeline_layout;
CHECK(vkCreatePipelineLayout(device, &plci, NULL, &pipeline_layout));
VkPipelineShaderStageCreateInfo stage = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = module, .pName = "main" };
VkComputePipelineCreateInfo pci = { .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = stage, .layout = pipeline_layout };
VkPipeline pipeline;
CHECK(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pci, NULL, &pipeline));
VkDescriptorPoolSize pool_size = { .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
.descriptorCount = 1 };
VkDescriptorPoolCreateInfo dpci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.maxSets = 1, .poolSizeCount = 1, .pPoolSizes = &pool_size };
VkDescriptorPool pool;
CHECK(vkCreateDescriptorPool(device, &dpci, NULL, &pool));
VkDescriptorSetAllocateInfo dsai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = pool, .descriptorSetCount = 1, .pSetLayouts = &set_layout };
VkDescriptorSet set;
CHECK(vkAllocateDescriptorSets(device, &dsai, &set));
VkDescriptorBufferInfo bi = { .buffer = buffer, .offset = 0, .range = VK_WHOLE_SIZE };
VkWriteDescriptorSet write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = set, .dstBinding = 0, .descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, .pBufferInfo = &bi };
vkUpdateDescriptorSets(device, 1, &write, 0, NULL);
VkCommandPoolCreateInfo cpci = { .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.queueFamilyIndex = family };
VkCommandPool cmd_pool;
CHECK(vkCreateCommandPool(device, &cpci, NULL, &cmd_pool));
VkCommandBufferAllocateInfo cbai = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.commandPool = cmd_pool, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1 };
VkCommandBuffer cmd;
CHECK(vkAllocateCommandBuffers(device, &cbai, &cmd));
VkCommandBufferBeginInfo begin = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
CHECK(vkBeginCommandBuffer(cmd, &begin));
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout,
0, 1, &set, 0, NULL);
vkCmdDispatch(cmd, (n + 63) / 64, 1, 1);
VkBufferMemoryBarrier barrier = { .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.buffer = buffer, .offset = 0, .size = VK_WHOLE_SIZE };
vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT,
0, 0, NULL, 1, &barrier, 0, NULL);
CHECK(vkEndCommandBuffer(cmd));
VkSubmitInfo submit = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.commandBufferCount = 1, .pCommandBuffers = &cmd };
CHECK(vkQueueSubmit(queue, 1, &submit, VK_NULL_HANDLE));
CHECK(vkQueueWaitIdle(queue));
printf("%u %u %u\n", mapped[0], mapped[1], mapped[127]);
int ok = mapped[0] == 1 && mapped[1] == 2 && mapped[127] == 128;
vkDestroyCommandPool(device, cmd_pool, NULL);
vkDestroyDescriptorPool(device, pool, NULL);
vkDestroyPipeline(device, pipeline, NULL);
vkDestroyPipelineLayout(device, pipeline_layout, NULL);
vkDestroyDescriptorSetLayout(device, set_layout, NULL);
vkDestroyShaderModule(device, module, NULL);
vkUnmapMemory(device, memory);
vkDestroyBuffer(device, buffer, NULL);
vkFreeMemory(device, memory, NULL);
vkDestroyDevice(device, NULL);
vkDestroyInstance(instance, NULL);
return ok ? 0 : 2;
}
Compile and run
On Linux (linking the Vulkan loader libvulkan):
cc -std=c11 add_one.c -lvulkan -o add_one
./add_one
On Windows (from an "x64 Native Tools" prompt, with VULKAN_SDK set by the LunarG installer):
cl /std:c11 /W3 add_one.c /I "%VULKAN_SDK%\Include" /link /LIBPATH:"%VULKAN_SDK%\Lib" vulkan-1.lib
add_one.exe
Both commands request C11 so designated struct initializers compile cleanly.
A working run prints 1 2 128 and exits with status 0.
If the program prints add_one.spv missing or invalid, confirm that you ran glslangValidator in the same working directory.
A negative VkResult on vkCreateInstance means the Vulkan loader or an enabled layer refused instance creation (often a missing ICD or broken driver install).
Reach for Vulkan compute when you need native cross-vendor GPU math without tying users to NVIDIA’s CUDA toolkit or AMD’s ROCm stack, or when your application already maintains a Vulkan device for rendering and wants compute on the same card.
If you want the same portable compute model with less boilerplate (or inside a browser), compare this against WebGPU and wgpu in GPU compute.