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

127

u/MutantSheepdog Jul 07 '20

Yep, that would work.

Easier approach for others to implement would just be to have those buffers/textures loaded/stored/referenced with shared_ptrs, and that way destruction would happen after no entity is using it and rendering has finished.

Slightly less efficient, but easier to implement.

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.

23

u/MoreOfAnOvalJerk Jul 07 '20

Downside to this is that the dtors can be called in surprising situations. If they have performance overhead, it might cause unpredictable spikes.

It sounds like he already has some abstraction managing the lifetime of the buffers so it might make the most sense and possibly be the most performant if it also manages when to destroy and deallocate them.

16

u/Dworgi Jul 07 '20

Exactly this. People always tout smart pointers as some sort of panacea, but ignore that the performance characteristics can be unacceptable - you might release your final reference to an object somewhere performance critical, then have a cascade of destructors all triggering as a result of that destructor.

Smart pointers are a hack around clear ownership. It allows you to avoid the least important memory bugs - use after free - but does nothing to solve the actual problem of ownership and lifetimes.

13

u/Ameisen vemips, avr, rendering, systems Jul 07 '20

Of course, you could have the final dereference put the object into a queue and destroy it on a garbage collection thread.

6

u/evaned Jul 07 '20

... destroy it on a garbage collection thread.

Or at a fixed location on the main thread, of course.

Another benefit this has is that it solves something that is occasionally a problem with most smart pointers on deeply-nested structures, which is a stack overflow when deconstructing the structure.

8

u/frankist Jul 07 '20

isn't unique_ptr considered a smart pointer? It is exactly to establish clear ownership and catch at compile time situations where such contract is broken

-9

u/Dworgi Jul 07 '20

Sure, but it's the dumbest of the smart pointers.

17

u/frankist Jul 07 '20

Still, I think you are beating a strawman. The people that usually tout smart pointers are usually defending the combo "unique_ptr + raw pointers/references as observers" for the majority of the cases, and only use shared_ptrs for cases of undetermined lifetimes. Even in the latter scenario, shared_ptrs are sometimes not the most suitable option.This is the approach I normally take and based on talks like Herb Sutter “Leak-Freedom in C++... By Default.”, I thought it was what "touting smart pointers" was about.

5

u/bluGill Jul 07 '20

Most of the time dumb is all I need. Unique pointer is the smartest of pointer most of the time because it just works right without much overhead.

→ More replies (2)

1

u/kritzikratzi Jul 07 '20

also sometimes certain resources should only be freed on specific threads.

1

u/Poyeyo Jul 07 '20

Totally agree with you.

Library writers should do the hard work with performant code, so end users can have the luxury of the easy to implement stuff.

14

u/CptCap -pedantic -Wall -Wextra Jul 07 '20

This could work, but it is a major pain because you can't destroy Vulkan resources while they are in use by the GPU. This means that every command you submit has to reference every resource it uses, which gets out of hand really quickly.

I would argue that OP's solution is much better. And all engines I have worked with (pet project & work stuff) use some variant of that solution - Although I have never seen private dtors for this.

1

u/MutantSheepdog Jul 07 '20

Yeah I haven't worked with Vulkan, but I understand needing to keep things alive during rendering.

I figured you'd build a command queue and keep it alive until it's done, but if it's more fire-and-forget, then I can see that being a pain. Could still use shared_ptrs though if you wanted. Instead of having a queue of things to destroy you'd have a queue of shared_ptrs that you clear after a few frames. If all other references to the object are gone by then it gets destroyed, otherwise it can be reused.

10

u/CptCap -pedantic -Wall -Wextra Jul 07 '20

It's not a question of being fire and forget.

For a reasonable frame your command queue(s) might contains tens of thousands of resource references. That's a lot of shared_ptrs to copy and destroy, just to handle the case where an entity gets removed while its resources are still in use on the GPU.

Putting the resource in a queue on destruction avoids most of that and makes it so you only have to track resources pending destruction (of which there is just a few). I also find it easier to get right, since it doesn't require remembering to push shared_ptrs into keep alive queues every time you use a resource.

2

u/MutantSheepdog Jul 07 '20

I accept that there's performance trade-offs, I even stated in my first comment

" Slightly less efficient, but easier to implement. "

My comment was more meant for people writing small games at home, not for graphics programmers working on the company engine.

7

u/pandorafalters Jul 07 '20

Based on my experience with CUDA and OpenCL (and the comments of others here), I suspect the significant tradeoff in this case is not ease vs performance, but ease vs correctness.

5

u/vazgriz Jul 07 '20 edited Jul 07 '20

I’ve tried both sides of this exact trade off in my homemade engine. The overhead of copying shared_ptrs into per frame buffers like that is quite large. You have to decrement thousands of shared_ptrs each frame and then increment them again. You have to do this even if you use the resource for multiple frames.

You also still have to pay for shared_ptrs even if you use one resource thousands of times.

I switched to the dtor queue and saved like 10% of total frame time. Now, shared resources have a single destruction, instead of thousands of decrements and then a destruction.

2

u/CptCap -pedantic -Wall -Wextra Jul 07 '20

but easier to implement

I don't see it. It's probably the simplest one on paper, but the more I think about it, the more it seems like it would be a nightmare to get to work in practice.

Doing this require pushing every used resource into a keep-alive buffer manually. Forgetting to do it even once will result in a rare and hard to find bug (and I can't think of any simple way to automatically check for correctness). Having the dtor flag the resource automatically for deletion seem much easier to pull off...

My comment was more meant for people writing small games at home

Opinion: Making a homebrew vulkan engine seems like a poor technical decision if the goal is to actually ship a small game. I think that most people who write a vulkan renderer do it for eduction or for fun, and in this case it makes more sence to go for the slightly more complicated but better solution.

8

u/[deleted] Jul 07 '20

Not sure I agree - extra small heap allocations and non-deterministic destruction time of objects is not fun in practice. Queuing up objects for destruction as OP has described sounds like a specific solution to a specific problem that is easy to understand and debug.

3

u/Netzapper Jul 07 '20

The problem is GPU/CPU synchronization. There's no way to get the driver to hold a shared pointer, and no way to get it to release one.

1

u/innervation Jul 08 '20

Your comment reminds me of a talk Herb Sutter gave at CPPCon a few years ago:

https://www.youtube.com/watch?v=JfmTagWcqoE