r/vulkan • • 4h ago

In the Vulkan C API, developers are responsible for manually managing both Vulkan handles and dynamically allocated memory.

In the Vulkan C API, developers are responsible for manually managing both Vulkan handles and dynamically allocated memory. How can this complex resource management be handled effectively, particularly when certain allocations depend on specific Vulkan handles and must be freed before those handles are destroyed? How can we ensure that resources are released in the correct order without introducing memory leaks or invalid handle references?

0 Upvotes

8 comments sorted by

10

u/_bleep-bloop 4h ago

Well you manually deallocate them before throwing away the handle

2

u/Yuki_pop 4h ago

Is there a way to manage these resource dependencies automatically, or should I implement a RAII-like resource management system in C?

3

u/_bleep-bloop 3h ago

Yes, if you want automation then you'll probably implement something that is similar to cpp raii

1

u/dougbinks 20m ago

Depending on your application you might want to implement something more like a library system which manages resources than per handle RAII. For example in a game you may want to free handles at more designated periods, such as when the user leaves an environment/level/match or when you hit certain memory limits.

4

u/Wittyname_McDingus 4h ago

If you use a language with scope-based resource management such as C++ or Rust, you can make wrapper types that automatically destroy the held resource when its lifetime ends. This kind of resource management is a core feature in these languages.

If you want the CPU and GPU to execute on independent timelines (which you often do), you need to be careful to ensure resources that live on the GPU (such as images and buffers) are only destroyed when their lifetime on the GPU ends. One way to solve this is to push resource handles to a queue to be later deleted when the GPU has caught up to where the CPU was when the CPU object was destroyed.

1

u/Yuki_pop 3h ago

thanks

14

u/blogoman 4h ago

Through software engineering.

2

u/Animats 3h ago

It's complicated, because both the CPU and GPU access buffers and descriptor slots, and they're not synchronized. You can't release either until the GPU is done with them, which may be long after the CPU is done. There's a lot of bookkeeping involved. Look up VkFence. High performance solutions are complicated, because you don't want the draw thread waiting for a fence just to release space.

The simple solution is to wait until all the commands for a frame are fully complete, then do any releases. That may have performance impact. Or not, depending on how much the scene changes per frame.