The Issue
I am currently working on a game. In this game,"game objects" of a certain type are stored in an std::vector. The Update (gameplay) code for these objects is executed on one thread, while rendering is handled by the main thread.
The vector of these "game objects" is passed by reference to the thread handling their Update code, so that the data is shared between threads. As such, some form of thread safety is required in order to prevent the render code from attempting to access memory that is being modified by the update code (which causes a crash).
Ideally, I would like to use a shared_mutex as part of these "game objects" stored within said vector. However, this won't compile and causes errors. My understanding is that this is because a mutex cannot be copied.
Is there a way to solve this problem that is performant, safe, and "not a nightmare to work with"?
The only viable solution I am seeing, is to prevent each specific type of object from updating and rendering at the same time. However, this would go some way to nullify the benefits of multithreading. I would estimate over 80% of game will be processing one singular type of object.
Basic Psuedocode to provide context below:
main(){
std::vector<Enemies> enemies;
std::thread(update_thread, std::ref(enemies), ... , ...);
while(true){
render_player();
render_enemies();
render_physics();
flip_to_display()
}
};
update_thread(std::vector<Enemies> &enemies, ... , ...){
while(true){
update_player();
update_enemies();
update_physics();
}
};
render_enemies(){
for(all enemies)
enemy.render();
}
update_enemies(){
for(all enemies)
enemy.update();
}
class Enemies{
//Would be nice to have the below, but afaik, not possible
std::shared_mutex mutex;
update(){
std::shared_lock<std::shared_mutex> lock(mutex);
//Write and Access data from enemy
}
render(){
std::shared_lock<std::shared_mutex> lock_shared(mutex);
//Only Access some data from enemy and draw it
}
}
NOTE: I am using visual studio 2015, so I can only use C++14(ish) compatible features.