garima721
garima721

Reputation: 323

How to lock a data structure modified by 2 threads which belong to 2 different classes

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?

Upvotes: 0

Views: 183

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76316

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.

Upvotes: 1

Related Questions