So I have a main application thread in my opengl application with all rendering and stuff. Now i need some really heavy calculation which takes about 2 3 seconds so I moved it to a seperate thread here is how I manage it:
std::atomic<bool> working = false;
void work(){
if(!working)
{
working = true;
std::thread worker(do_work);
worker.detach();
}
else
{
// Some Updations
}
}
void do_work()
{
// The actual work
// working = false;
}
Now i call work every frame and the actual work gets dispatched automatically once the previous one has finished.
Now my question is what will be some ways to optimize this? Some ideas that come to my mind are have a thread pool but I am not sure if that is worth the trouble implementing? Or is there any other way?
CodePudding user response:
You could use std::launch as some people have suggested. Or you could do a google for "c thread pool library" and probably find something waiting for you.
But the reality is simple: writing a thread pool is close to trivial and is a good exercise. So you could write your own and learn something. As has been suggested, you can dispatch via some sort of message queue.
A work queue would be any sort of mutex & cond_var - managed FIFO, and then you can have multiple readers and multiple writers. The entries in the queue can be any sort of runnable or bound function (such as a lambda).
Fun to write and you can toss into your person library for years to come.