OpenGL
The long-standing cross-platform graphics API. Since OpenGL 4.3 (and OpenGL ES 3.1) it has compute shaders in GLSL that read and write buffers and images, the simplest way to add GPGPU to an existing OpenGL app without bringing in a separate compute API. Note that WebGL does not expose compute shaders; use WebGPU there instead.
KhronosC/C++ · GLSLcross-vendorcompute shaderswidely supported
Install
# Install GPU drivers plus a loader + windowing/context library
# Linux (Ubuntu):
sudo apt-get install -y libglew-dev libglfw3-dev
# requires an OpenGL 4.3+ context at runtime
Hello, GPU
double.comp.glsl: an OpenGL 4.3 compute shader
// double.comp.glsl: GLSL compute shader
#version 430
layout(local_size_x = 64) in;
layout(std430, binding = 0) buffer Data { float v[]; };
void main() {
uint i = gl_GlobalInvocationID.x;
v[i] = v[i] * 2.0;
}
/* Host (C/C++, abbreviated, inside a current GL 4.3 context):
GLuint s = glCreateShader(GL_COMPUTE_SHADER);
glShaderSource(s, 1, &src, NULL); glCompileShader(s);
GLuint p = glCreateProgram(); glAttachShader(p, s); glLinkProgram(p);
GLuint ssbo; glGenBuffers(1, &ssbo);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
glBufferData(GL_SHADER_STORAGE_BUFFER, n*4, data, GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);
glUseProgram(p);
glDispatchCompute(n / 64, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, n*4, data); // doubled */
Run it:
# compile/link the host program against -lGLEW -lglfw -lGL, then run it