Can I use cl_context to compare OpenCL contexts?

Viewed 124

If I have two cl_contexts c1 and c2, can I equality compare them (c1 == c2) to figure out if they represent different contexts? In particular:

  • Is it guaranteed that if c1 == c2, they represent the same context?
  • Is it guaranteed that if c1 != c2, they represent different contexts?

Any references to relevant documentation is appreciated.

1 Answers

The specification doesn't explicitly state this, but I don't see how your first test could possibly be false. How would the runtime know which of the 2 contexts is meant if they have the same handle/pointer value? The C type system does not allow for types which are ==-comparable but aren't actually equal if == evaluates to true. (In C++, operator overloading would make this possible of course.)

For the second test, I'd be curious to know from where you'd be expecting to obtain different cl_context handles to the same context? For functions such as clGetCommandQueueInfo(queue, CL_QUEUE_CONTEXT, …), the specification is probably clear enough: "Return the context specified when the command-queue is created." I don't think that can be interpreted as "Can return a different handle to the same context than the one that was specified when the command-queue was created." So I don't see under what circumstances you might end up with 2 different handles to the same context.

You don't ask, "could 2 calls to clCreateContext() with identical arguments return the same context?" - This is related to your first question but slightly different. As far as I'm aware, contexts are stateless from an API perspective (aside from reference count, which is opaque - you must balance releases with retains or behaviour is undefined), and the specification doesn't state that the context will be unique, so I suppose some implementations might choose to return the same context twice in such a case. (It seems unlikely though, as the question would be: why?) If this is a concern, make sure to pass unique user_data pointers to each of your clCreateContext() calls.

Finally, I don't actually see anywhere in the specification that defines whether cl_context be comparable with == in the first place. However, the clCreateContext family of functions may return NULL in case of an error, which implies that cl_context can't really be anything other than a typedef for a pointer type. Additionally, the official C++ wrapper, cl2.hpp, defines == and != operators on the wrapper classes which compare the underlying C handles for the OpenCL objects with == and !=.

So I think it's pretty safe to say that both conditions hold.

Related