0
votes

Basically, I have a std::map which is shared between 2 classes. Thread1 of class A continuously monitors this map for some info and take action accordingly, and Thread2 of class B updates this map upon receiving some data on some socket.

Now how can I prevent this map from corruption, since it is modified by 2 threads of 2 different classes?

One way is that i can keep an extra bool variable per entry in map, and set it True before modifying map, and False after modification. If another thread (Thread2) finds this bool variable to be True already, then it knows that Thread1 is modifying it, and should wait. But is this method efficient?

1
I guess it is efficient as you are going to more granular level of poer entry it will prevent the threads from bring locking the entire map. it will only lock that entry which it is modifing.But the performance of your code depends on how complex logic do you have in the block.nikhil mehta
@nikhil : Okay and, what should I use to wait for bool variable to be false, if its already true?garima721

1 Answers

1
votes

You should protect the map with a std::mutex. Protecting it with a bool, then thinking about what to do when the bool indicates "taken", etc. - will just mean you're trying to reimplement mutex. You probably can't do it more efficiently than the library version.

Additionally, in any situation where one of the threads needs to wait for a change in the map to proceed, use (one or more) std::condition_variables.