Tiger Hwang Tiger Hwang - 8 months ago 56
C++ Question

clSetEventCallback, should the event be retained explicitly?

I have a case where after enqueuer a kernel, an event is obtained and set call back for profiling. For example:

cl::Event event;
cl::CommandQueue queue(context, devices[0], 0, &err);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(4,4), cl::NullRange, NULL, &event);
event.setcallback(CL_COMPLETE, &EventCallback);

Where Callback is a function to check kernel execution time.

void CL_CALLBACK EventCallback(cl_event event, cl_int, void* pUserData)
cl_int err = CL_SUCCESS;
cl_ulong submitted = 0, end = 0;
clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start, NULL);
clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, NULL);

I ignored the return error code checking here, but sometimes clGetEventProfilingInfo() method return CL_INVALID_EVENT. If run debug and put break point inside callback, this does not happen.

I think this may because the cl::Event object leaved scope too fast and was released before callback is called, but cannot confirm it.

So my question is should the event be retained explicitly before leaving the scope? Or there can be other reasons?


I figure it out, before set callback, call clRetainEvent(), and in the end of EventCallback, call clReleaseEvent(), so the event will be valid until end of callback. Without release it in the end, debugger will report it as memory leak.