Skip to content

Commit

Permalink
Merge pull request #1011 from fabiomestre/fabio/fix_opencl_leak
Browse files Browse the repository at this point in the history
[OpenCL] Fix memory leak
  • Loading branch information
kbenzie committed Nov 7, 2023
2 parents 7db941d + 55409e4 commit 612a263
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
16 changes: 10 additions & 6 deletions source/adapters/opencl/adapter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,29 @@

struct ur_adapter_handle_t_ {
std::atomic<uint32_t> RefCount = 0;
std::mutex Mutex;
};

ur_adapter_handle_t_ adapter{};

UR_APIEXPORT ur_result_t UR_APICALL urInit(ur_device_init_flags_t,
ur_loader_config_handle_t) {
cl_ext::ExtFuncPtrCache = new cl_ext::ExtFuncPtrCacheT();
return UR_RESULT_SUCCESS;
}

UR_APIEXPORT ur_result_t UR_APICALL urTearDown(void *) {
if (cl_ext::ExtFuncPtrCache) {
delete cl_ext::ExtFuncPtrCache;
cl_ext::ExtFuncPtrCache = nullptr;
}
return UR_RESULT_SUCCESS;
}

UR_APIEXPORT ur_result_t UR_APICALL
urAdapterGet(uint32_t NumEntries, ur_adapter_handle_t *phAdapters,
uint32_t *pNumAdapters) {
if (NumEntries > 0 && phAdapters) {
std::lock_guard<std::mutex> Lock{adapter.Mutex};
if (adapter.RefCount++ == 0) {
cl_ext::ExtFuncPtrCache = std::make_unique<cl_ext::ExtFuncPtrCacheT>();
}

*phAdapters = &adapter;
}

Expand All @@ -50,7 +51,10 @@ UR_APIEXPORT ur_result_t UR_APICALL urAdapterRetain(ur_adapter_handle_t) {
}

UR_APIEXPORT ur_result_t UR_APICALL urAdapterRelease(ur_adapter_handle_t) {
--adapter.RefCount;
std::lock_guard<std::mutex> Lock{adapter.Mutex};
if (--adapter.RefCount == 0) {
cl_ext::ExtFuncPtrCache.reset();
}
return UR_RESULT_SUCCESS;
}

Expand Down
2 changes: 1 addition & 1 deletion source/adapters/opencl/common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ struct ExtFuncPtrCacheT {
// piTeardown to avoid issues with static destruction order (a user application
// might have static objects that indirectly access this cache in their
// destructor).
inline ExtFuncPtrCacheT *ExtFuncPtrCache;
inline std::unique_ptr<ExtFuncPtrCacheT> ExtFuncPtrCache;

// USM helper function to get an extension function pointer
template <typename T>
Expand Down

0 comments on commit 612a263

Please sign in to comment.