A quick question for you guys.
I’ve read a lot of OpenCL code and I’m always surprised about the initialization part.
Especially about the initialization of the platform, device, and context.
It’s never the same order and it seems that you can create a context from nothing and then get the device from the context.
Or you can do the opposite: get the device and then create the context on the device…
It’s a bit confusing and I’d like to know what is the correct solution.
If both are correct, what is the reason to use one or the other?
After reading the programming guide, I came up with the following initialization:
This is the correct way to do it if you want / need explicit control about which (of possible multiple) platform / device to use. Personally, this is what I prefer. However, if you either know that there will always be only one platform / device on the machine you’re running your code on, or if you just don’t care about the exact platform / device as long as it’s e.g. a GPU device, you can either call clCreateContext() without specifying a platform (and thus without a device), in which case the platform and device chosen is implementation-defined, or call clGetDeviceIDs() with CL_DEVICE_TYPE_GPU for any / all platforms. You may also call clGetDeviceIDs() with a NULL platform, in which case the behavior again is implementation-defined.
My recommendation is to always be explicit and not to rely on implementation-specific behavior to make your code portable and robust.