Reputation: 2603
I am doing some development trying out C++11 threads. I would like to run some code in an asynchronous thread and when that code is done I would like to run other code on the main thread But only when it's done!
This is because the things I would like to run async is loading OpenGL stuff, and it's a bit tricky with the OpenGL contexts when doing threads, as far as I know it's pretty much a don't run the same context in different threads.
However I would like to create a loader thread, which loads collada files and the time consuming stuff here really is to parse the file and set up the data and all of that I could (technically) do in a separate thread and then just do the opengl specific tasks on the main thread. (this is my initial thought and I might just be going at it the wrong way)..
So I am thinking that if I could detach one thread async to load up the collada file and fill the out the data, then once it's finished I'll invoke on the main thread to bind buffers, set up shaders and so on. I can do it without threads, but would be pretty smooth to load new data in the background without GL freaking out..
So I'll try to line up the steps I want to do:
I do have all of it working synchronous and what I want is a way to do some things once the detached async thread finishes.
Any ideas or of course constructive criticism of my thinking here :P is greeted with a warm welcome! I might be thinking about it all the wrong way, I've been thinking about doing something like an observer pattern but I don't really know how to tackle it the best way. I wouldn't mind threading the OpenGL stuff, but it seem a bit like asking for trouble..
Upvotes: 4
Views: 3570
Reputation: 126552
If I understood your use case correctly, then I think the std::async()
function, started with the std::launch::async
policy to make sure the operation is really started on another thread, does just what you want:
// Your function to be executed asynchronously
bool load_meshes();
// You can provide additional arguments if load_meshes accepts arguments
auto f = std::async(std::launch::async, load_meshes);
// Here, the main thread can just do what it has to do...
// ...and when it's finished, it synchronizes with the operation
// and retrieve its result (if any)
bool res = f.get(); // res will hold the return value of load_meshes,
// or this will throw an exception if one was
// thrown inside load_meshes()
if (res)
{
// ... and then it will go on doing the remaining stuff on the main thread
}
One tricky thing to be aware of here, is that you should always assign the return value of std::async()
to some variable (of type std::future<T>
), where T
is the type returned by load_meshes()
. Failing to do so will cause the main thread to wait until load_meshes()
is finished (thus, it's as if the function was invoked in the main thread).
Upvotes: 6