@@ -27,6 +27,10 @@ namespace ze_lib
2727 }
2828 }
2929 bool delayContextDestruction = false ;
30+ bool loaderTeardownCallbackReceived = false ;
31+ void teardownCallback () {
32+ loaderTeardownCallbackReceived = true ;
33+ }
3034 #endif
3135 bool destruction = false ;
3236
@@ -39,6 +43,14 @@ namespace ze_lib
3943 // /////////////////////////////////////////////////////////////////////////////
4044 __zedlllocal context_t ::~context_t ()
4145 {
46+ if (debugTraceEnabled) {
47+ debug_trace_message (" ze_lib Context Destructor" , " " );
48+ }
49+ // Call the teardown callbacks
50+ for (auto &callback : teardownCallbacks) {
51+ callback ();
52+ }
53+ teardownCallbacks.clear ();
4254#ifdef DYNAMIC_LOAD_LOADER
4355 if (loader) {
4456 FREE_DRIVER_LIBRARY ( loader );
@@ -346,6 +358,7 @@ namespace ze_lib
346358 if (!delayContextDestruction) {
347359 std::atexit (context_at_exit_destructor);
348360 }
361+ zelRegisterTeardownCallback (teardownCallback);
349362 #endif
350363 return result;
351364 }
@@ -397,6 +410,13 @@ zelSetDriverTeardown()
397410{
398411 ze_result_t result = ZE_RESULT_SUCCESS ;
399412 if (!ze_lib::destruction) {
413+ if (ze_lib::context) {
414+ // Call the teardown callbacks
415+ for (auto &callback : ze_lib::context->teardownCallbacks ) {
416+ callback ();
417+ }
418+ }
419+
400420 ze_lib::destruction = true ;
401421 }
402422 return result;
@@ -476,6 +496,18 @@ void stabilityCheck(std::promise<int> stabilityPromise) {
476496}
477497#endif
478498
499+ ZE_DLLEXPORT ze_result_t ZE_APICALL
500+ zelRegisterTeardownCallback (
501+ zel_teardown_callback_t callback // [in] Pointer to the callback function
502+ ) {
503+ ze_result_t result = ZE_RESULT_SUCCESS ;
504+ if (nullptr == callback) {
505+ return ZE_RESULT_ERROR_INVALID_ARGUMENT ;
506+ }
507+ ze_lib::context->teardownCallbacks .push_back (callback);
508+ return result;
509+ }
510+
479511/* *
480512 * @brief Checks if the loader is in the process of tearing down.
481513 *
@@ -497,6 +529,9 @@ zelCheckIsLoaderInTearDown() {
497529 return true ;
498530 }
499531 #if defined(DYNAMIC_LOAD_LOADER) && defined(_WIN32)
532+ if (ze_lib::loaderTeardownCallbackReceived) {
533+ return true ;
534+ }
500535 std::promise<int > stabilityPromise;
501536 std::future<int > resultFuture = stabilityPromise.get_future ();
502537 int result = -1 ;
0 commit comments