What is the correct use of a Mutex? How do I know what it is protecting? Does it stop all threads from running for the locked period?
For example I have a singleton that contains a list of objects.
class Foo
{
// Pretend this is a singleton.
std::list<Object>* GetObjects() { return &objects; }
void Reset() { for ( auto iter = objects.begin(); iter != objects.end(); ++iter ) { delete *iter; } }
std::list<Object> objects;
};
In a separate class I have a update method. This is run in a seperate thread.
class Bar
{
void Update()
{
std::list<Object>* objects Foo.GetObjects();
for(auto iter = objects.begin(); iter != objects .end(); ++iter )
iter->SetTransform(50,50,50);
}
};
My Problem is that I want to call Reset() on Foo, and delete all the objects. But my Bar class is updating all these objects. So if it is in the middle of a update method it may be trying to modify a object that has been deleted.
How do I prevent this?
Can I just create a Mutex in reset function and lock it before deleting and unlock it after? Something like this:
void Reset()
{
Mutex mutex; mutex.Lock()
for ( auto iter = objects.begin(); iter != objects.end(); ++iter )
delete *iter;
mutex.Unlock();
}
Does this let the other class know these resources are locked? I am not sure how the mutex knows what information to protect. How does it know that it needs to lock the list in the singleton class.
Btw this is all pseudo code so there is syntax errors and missing information.