Game Development Reference
In-Depth Information
stringstream playerInputStream;
GetPlayerInput(playerInputStream);
EvaluateInput(playerInputStream);
bool playerWon = true;
for (auto& enemy : m_enemies)
{
playerWon &= enemy->IsAlive() == false;
}
if (playerWon)
{
SetPlayerWon();
}
}
if (GetPlayerWon())
{
SerializationManager::GetSingleton().ClearSave();
cout << "Congratulations, you rid the dungeon of monsters!" << endl;
cout << "Type goodbye to end" << endl;
std::string input;
cin >>input;
}
}
The bold lines show the updates to this method to support the mutex protection around our shared
variables. There's an attempt to follow best practice by using a local variable to work out if the player
has won the game before calling the SetPlayerWon method. You could wrap the entire loop in a mutex
lock mechanism, but this would slow your program, as both threads would be spending longer in a
state where they were simply waiting for locks to be unlocked and not executing code.
This extra work is one reason why splitting a program into two separate threads does not give a
100% increase in performance as there is some overhead to waiting for lock to synchronize access
to shared memory between the threads. Reducing these synchronization points is key to extracting
as much performance as possible from multithreaded code.
Threads and mutexes make up a low-level view of multithreaded programming. They represent
abstract versions of operating system threads and locks. C++ also provides higher level threading
abstractions that you should use more often than threads. These are provided in the promise and
future classes.
Using Futures and Promises
The future and promise classes are used in a pair. The promise executes a task and places its result
in a future . A future blocks execution on a thread until the promise result is available. Fortunately
C++ provides a third template to create a promise and future for us so that we don't have to
manually do this over and over.
 
Search WWH ::




Custom Search