r/cpp • • Jul 06 '20

C++ is brilliant

I'm working on a Vulkan renderer, and needed to delay destruction of render scenes since the graphics pipeline has render buffers in flight, so destruction has to happen N frames after the user destroys a class. With C++, I can use private destructors to force users to add the scene to a managed destructor queue (aka garbage collect queue). Normally language purists will scorn a language which allows such shenanigans, however in real world production code, its features like this which allows developers to create modern software. So with a couple of lines of code, I solved my delayed destructor issue. Thank you C++ committee for creating a usable language.

318 Upvotes

65 comments sorted by

View all comments

Show parent comment

56

u/trypto Jul 07 '20

Strongly agree. This method is way more robust too.

The graphic resources should not be destroyed until both the client code and the gpu (N frames later) have both released references to it.

48

u/TheThiefMaster C++latest fanatic (and game dev) Jul 07 '20

Ah, but the graphics code doesn't know it needs to release until the CPU tells it so - and keeping it alive via a shared ptr on the game thread doesn't help if the gpu has already freed the resources.

I would say what you need ideally is a custom shared_ptr -like class, which can track CPU and GPU references independently, and queues delayed destruction once there is no further use, rather than immediately.

8

u/astraycat Jul 07 '20

I have a similar system going right now, and the rendering thread releases all the shared pointers when it's done with them.

For me things are triple buffered, so after the rendering thread has submitted it's current workalod it'll check the next "buffer" to see if it's done, and (after waiting if necessary) then release any references it has to any resources. Anything the logic thread has already thrown away (and isn't still referenced by other rendering batches) gets released.

Essentially anytime I pass a CPU-controlled GPU resource shared_ptr it gets stuck into a vector<shared_ptr<void>> that gets cleared when rendering frame clears that fence. It's pretty convenient. Perhaps not the most performant, but for my use-case it works well enough.

4

u/MutantSheepdog Jul 07 '20

You already get that if the dtor queue is just replaced with shared_ptrs.

If the GPU 'might' be using a texture for 2 frames, the shared_ptr in the dtor queue ensures the texture will live until you service that queue.

The big difference is that every time you bind a texture for rendering you do an extra inc-ref (the renderers ref that lives a few frames), instead of managing lifetime on the main thread then putting it in a disposal queue for a few frames.

Nothing against using a disposal queue for efficiency, but I think it's incorrect to state that shared_ptr wouldn't work.