【发布时间】:2013-02-03 14:31:02
【问题描述】:
我想转储 unordered_map 的键,同时能够同时添加和删除元素。完全转储需要 4 秒,太长了。是否可以在单独的线程中转储,如下所示:
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
}
在主线程中我有:
pthread_mutex_lock( &mutex );
map.erase(iter);
unordered map的erase方法是否会出问题,因为iterator在擦除后会失效。
还有其他安全的并行转储方式吗?
【问题讨论】:
-
“do_this”到底是做什么的?
-
@Mats:没关系。
-
我在寻找“是否有其他方法可以解决‘需要 4 秒’”,而不是直接回答这个问题。
-
do_this执行 fstream 操作。所以我不能让它更快。
标签: c++ multithreading unordered-map