How to effectively swap OpenCL memory buffers?

buffer, opencl, swap

Solution

You don't need to, just set the right kernel args using `clSetKernelArg` before enqueuing your kernel a second time (using `clEnqueueNDRangeKernel`). The buffers will stay on the device, nothing will be copied back to the host.

Your buffer has to be created with `CL_MEM_READ_WRITE` in this case of course.

Problem

Exactly as the title suggests I am looking for how to effectively swap two OpenCL buffers. My kernel uses two gloabl buffers, one as input and one as output. However, I invoke my kernel in a for loop with the same NDRange, each time setting the kernel arguments, enqueueing the kernel, and swapping the buffers because the previous output buffer will be the input buffer seed for the next iteration. What is the appropriate way here, to swap these two buffers? I imagine that copying the buffer back to the host to one of the already malloc'd arrays and copying it into the next input buffer using `clEnqueueWriteBuffer()` and `clEnqueueReadBuffer()` is an inefficient way to go. Otherwise I am just using a temporary `cl_mem` variable to do my swapping.

Original source