What provoked my question
For some OpenGL based work where some tasks need to be executed on the GL thread, I set up a
juce::Array<std::function<void(juce::OpenGLContext&)>, juce::CriticalSection> executeInRenderCallback
as a class member to which I can add lambdas that need to be executed on the gl thread at any time from any thread and check if there is anything in the array at every OpenGL render callback and then execute this stuff like this:
for (auto &glThreadJob : executeInRenderCallback) glThreadJob (openGLContext); executeInRenderCallback.clearQuick();
This seemed to work for weeks until I reached an edge case after some recent code additions where there were 9 lambdas to execute - I get a segfault when the first function should be executed. As I think that the array reallocates its storage after having reached a size of 8 elements I strongly suspect this could be the source of that issue.
However, I’m not sure why this is a problem. I always understood
std::function as some kind of syntactical nice wrapper around a function pointer (that should be trivially copyable) which is pointing to the lambda function, which itself should be compiled at compiletime and should not be destructed like a real object, so I’m not sure why it should not be valid anymore after resizing the array and with that copying the std::function object? I suspect I could be wrong with this assumption…
My actual question
Am I assuming it right that storing the lambda in an
Array is likely to be the source of my bug? If yes, what is the best kind of container to store a various number of lambdas for later execution? Is an
OwnedArray the way to go? How do others solve the problem of setting up a queue to execute functions in the GL render thread?