C Specification

To register a callback function with a context that is called when the context is destroyed, call the function

cl_int clSetContextDestructorCallback(
    cl_context context,
    void (CL_CALLBACK* pfn_notify)(cl_context context, void* user_data),
    void* user_data);
clSetContextDestructorCallback is missing before version 3.0.


  • context specifies the OpenCL context to register the callback to.

  • pfn_notify is the callback function to register. This callback function may be called asynchronously by the OpenCL implementation. It is the application’s responsibility to ensure that the callback function is thread-safe. The parameters to this callback function are:

    • context is the OpenCL context being deleted. When the callback function is called by the implementation, this context is no longer valid. context is only provided for reference purposes.

    • user_data is a pointer to user-supplied data.

  • user_data will be passed as the user_data argument when pfn_notify is called. user_data can be NULL.


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. If a context callback function was specified when context was created, it will not be called after any context destructor callback is called. Therefore, the context destructor callback provides a mechanism for an application to safely re-use or free any user_data specified for the context callback function when context was created.

clSetContextDestructorCallback returns CL_SUCCESS if the function is executed successfully. Otherwise, it returns one of the following errors:

  • CL_INVALID_CONTEXT if context is not a valid context.

  • CL_INVALID_VALUE if pfn_notify is NULL.

  • CL_OUT_OF_RESOURCES if there is a failure to allocate resources required by the OpenCL implementation on the device.

  • CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by the OpenCL implementation on the host.

See Also

Document Notes

For more information, see the OpenCL Specification

This page is extracted from the OpenCL Specification. Fixes and changes should be made to the Specification, not directly.

Copyright 2014-2023 The Khronos Group Inc.

SPDX-License-Identifier: CC-BY-4.0