callbackopenclobject-destruction

What happens when you set the same OpenCL callback more than once on the same object?


OpenCL has several API functions to set callback functions - for events, for buffers/memory objects, for contexts and maybe more.

What happens if you invoke one of these functions, more than once, on the same object? Is this specified somehow? Is it just undefined?


Solution

  • It is specified. Nothing forbids registering multiple callbacks, and the documentation explains the behaviour with this in mind. Whether the behaviour is correct or introduces any issues of "double deletion" kind (or other) is up to the implementation of callbacks and whether the user registers/uses them correctly (in case of destructors, particularly, in the correct order).

    From the documentation you provided for cl_mem destructors (bold emphasis mine):

    Each call to clSetContextDestructorCallback registers the specified callback function on a destructor callback stack associated with context. The registered callback functions are called in the reverse order in which they were registered. The registered callback functions are called and then the memory object’s resources are freed and the memory object is deleted. ...

    and for cl_context destructors:

    Each call to clSetContextDestructorCallback registers the specified callback function on a destructor callback stack associated with context. The registered callback functions are called in the reverse order in which they were registered. ...

    For events, you can also use multiple callbacks, but note that in this case the order in which they run is undefined:

    Each call to clSetEventCallback registers the specified user callback function on a callback stack associated with event. The order in which the registered user callback functions are called is undefined.

    Also, there's no restriction against registering the same function as a callback more than once for the same object. For example, in case of events, a single function could implement callbacks for different command execution statuses. Then, it is registered several times with different command_exec_callback_type's, which get passed into event_command_status parameter of the function. Again, the correctness of this is up to the user.