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?