From 8e6589ec6772e39d01ce4d43f2644684bfd232a7 Mon Sep 17 00:00:00 2001 From: Attila Uygun Date: Sat, 24 Jun 2023 10:01:20 +0200 Subject: [PATCH] Fix memory leak when canceling tasks --- src/base/task_runner.h | 18 ++++++++++++------ src/engine/renderer/vulkan/renderer_vulkan.cc | 10 ++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/base/task_runner.h b/src/base/task_runner.h index 44ae501..79ba150 100644 --- a/src/base/task_runner.h +++ b/src/base/task_runner.h @@ -18,16 +18,15 @@ namespace internal { // one that returns via an output parameter. template void ReturnAsParamAdapter(std::function func, - ReturnType* result) { + std::shared_ptr result) { *result = func(); } // Adapts a ReturnType* result to a callblack that expects a ReturnType. template void ReplyAdapter(std::function callback, - ReturnType* result) { + std::shared_ptr result) { callback(std::move(*result)); - delete result; } } // namespace internal @@ -57,13 +56,20 @@ class TaskRunner { std::function task, std::function reply, bool front = false) { - auto* result = new ReturnType; + auto result = std::make_shared(); return PostTaskAndReply( from, std::bind(internal::ReturnAsParamAdapter, std::move(task), result), - std::bind(internal::ReplyAdapter, std::move(reply), - result), front); + std::bind(internal::ReplyAdapter, std::move(reply), result), + front); + } + + // Posts a task to delete the given object. + template + void Delete(Location from, std::unique_ptr object) { + std::shared_ptr owned = std::move(object); + PostTask(HERE, [owned]() {}); } void CancelTasks(); diff --git a/src/engine/renderer/vulkan/renderer_vulkan.cc b/src/engine/renderer/vulkan/renderer_vulkan.cc index 6208e47..fe69277 100644 --- a/src/engine/renderer/vulkan/renderer_vulkan.cc +++ b/src/engine/renderer/vulkan/renderer_vulkan.cc @@ -414,10 +414,7 @@ uint64_t RendererVulkan::CreateGeometry(std::unique_ptr mesh) { VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT)); - task_runner_.PostTask(HERE, [&, mesh = mesh.release()]() { - // Transfer mesh ownership to the background thread. - std::unique_ptr own(mesh); - }); + task_runner_.Delete(HERE, std::move(mesh)); semaphore_.release(); return last_resource_id_; @@ -506,10 +503,7 @@ void RendererVulkan::UpdateTexture(uint64_t resource_id, 0, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)); - task_runner_.PostTask(HERE, [&, image = image.release()]() { - // Transfer image ownership to the background thread. - std::unique_ptr own(image); - }); + task_runner_.Delete(HERE, std::move(image)); semaphore_.release(); }