struct Data
{
...
CRITICAL_SECTION valLock;
}
std::map<int, Data> mp;
CRITICAL_SECTION mpLock;
I am currently using two critical sections to make this thread safe.
I have to lock both map
and Data
for updating a Data
//Lock mpLock
//Lock mp[key1].valLock
mp[key1].something = something_new;
//unlock mp[key1].valLock
//unlock mpLock
I looked into intel's concurrent hashmap, which does not need two locks and handles this internally.Is there any other way, if i don't want to use intel's tbb. I have only c++ 98
support.Can use boost
though. Looked into boost::shared_mutex
, but could not relate how i can use it in my current scenario.
EDIT:
Is the lock on container really required? Can't i use Data::valLock
to read/write Data
.Any insertion in mp
is not going to affect the existing iterators, so no lock is needed.Any deletion from mp
will be preceded with Data::valLock
.What cases could be missed here?
EDIT 2:
UpdateThread()
{
//Lock mp[key].valLock
mp[key].a = b; //Line 1
//unlock mp[key].valLock
}
ReadThread()
{
//Lock mp[key].valLock
something = mp[key].a; //Line 2
//unlock mp[key].valLock
}
So i am thinking that Line 2 can execute only if Line 1 has completed(or vice versa) i.e. mp
has been updated(along with the map internals).So is it not safe? If not then it means if one thread modifies mp[key1], and another reads mp[key2], this is data race?