I want to dump the keys of an unordered_map while being able to simultaneously add and erase elements. It takes 4 seconds to dump entirely, it’s too long. Is it possible to dump in separate thread, like this:
while (1) {
pthread_mutex_lock( &mutex );
if(iter!=map.end()){
x=iter->first
iter++;
}
pthread_mutex_unlock( &mutex );
do_this(x); // this takes time to complete
}
while in the main thread I have:
pthread_mutex_lock( &mutex );
map.erase(iter);
Does the erase method of unordered map make problem, since the iterator will be invalid after erasing.
Is there any other safe way to dump in parallel?
For
unordered_map(and associative containers in general), theerase()member function does not invalidate iterators and references to other elements than the removed one(s).However, here you may be erasing an element and invalidate iterators to it while your loop holds an iterator to that element: for instance, if you happen erase the element which is referenced by the next iterator that is going to be dereferenced in your loop.
Hence, you need to take care that the element you are removing is not referenced by the iterator you are going to process in the next loop of your
whilecycle:Where
iteris the iterator variable used in the loop.