i plan to make a little game/simulation that makes use of 2 threads:
1. main thread, responding to input and render graphics
2. a spawned sub-thread to main, doing all the animation/physics
1 2 3 4
struct World {
mutex m1;
/* some data describing the objects in the game */
} world;
the main thread can run easily parallel to the animation thread, only when it comes to generating the graphics wokload out of the world, i need to lock the mutex. when done, i can release the mutex and draw the world (using openGL) parallel again to the animation thread. the 2nd thread will be created once and it will stay as long as main is running. which means it can run kind of "at its own pace" (for example, main uses 60FPS, animation thread at about 150 or so ...)
is this a good idea?
is there a fundamentally better approach?
do i have to mind anything else?
(this is my first threading app, so i appreciate any advice ;-) ...)
it sounds about right to me. You don't actually have 2 threads that you handle, here. The 'main' thread is the one you have used forever, the single-threaded thread, 'main'. It still exists:
int main()
{
blah blah;
start thread(function, params); //this will now go off on its own and start running.
this statement will execute while the thread is running;
then this one, this is the main thread;
and so on;
}
so you will only be 'aware' of one thread object, is what I am saying.
my advice is to do something simple with a couple of threads to get your feet wet on the syntax and getting it working. Don't kick off a big project without playing a bit to get some fundamentals.
struct World {
mutex lockable;
bool running = true;
/// rest of the world here ...
} world;
void Simulate(World& world)
{
while (world.running)
{
{
/// block other threads to access world
lock_guard<mutex> guard(world.lockable);
/// simulate the world here, move objects, etc ...
}
/// simulate other stuff here (NOT world)
/// pause a little ...
this_thread::sleep_for(milliseconds(16))
}
}
void Render(World& world)
{
Batch b;
{
/// block other threads to access world
lock_guard<mutex> guard(world.lockable);
/// process world for visualization
b = GenerateBatch();
}
/// visualize world (without having to access world)
Draw(b);
}
int main()
{
/// start simulation
thread sim(Simulate, ref(world));
/// world.running is under control (menu, window Xed out, etc)
while (true)
{
/// some input processing here ...
/// this runs with vsync on, 60fps
Render(world);
}
/// stop sim
{
/// block other threads to access world
lock_guard<mutex> guard(world.lockable);
world.running = false;
}
sim.join();
return 0;
}