Reputation: 190
I am currently working on a game in C++ which is supposed to use multithreading to handle bot instances. The Bot class has a member function start(), which calls the bot's function walk() in a new thread. This is my attempt (in excerpts:)
void Bot::walk(Physics& physics)
{
// do stuff
std::cout << "call to walk() function" << std::endl;
}
void Bot::start(Physics& physics)
{
std::thread m_thread(&Bot::walk, this, std::ref(physics));
m_thread.join();
}
In another class which handles the initialization of the game, all bot instances are started like this: (m_bots is a vector of Bots)
void Level::start()
{
// Start all Bots
for(auto it: m_bots)
{
it->start(*m_physics);
}
}
On startup the game window opens as usual but then continues to freeze. The console output shows that the walk() function is called though.
What thread-specific catch am I missing?
I hope these excerpts cover all the relevant information. If this is not the case, please let me know!
Upvotes: 1
Views: 1735
Reputation: 76523
Joining a thread blocks until the thread finishes. As a result, Bot::start
won't return until the thread that it spawns finishes, so only one thread will run at a time.
Someone will probably tell you that the solution is to change join()
to detach()
. That's not really the solution, unless your design calls for a bunch of free-running threads; if you care about when they finish, join()
is the way to do it, just not there.
One approach is to create an object of type std::vector<std::thread>
and launch all of the thread with calls to Bot::start
. After the threads are running you can join all the spawned threads.
Upvotes: 6