在锁下清除 std::map 与移动到临时对象
Clearing std::map under a lock vs moving to a temp object
我正在使用 std::map 并且其中包含大量元素。如果我需要清除地图,我可以在上面调用 clear() 。清除可能需要一些时间,特别是如果在多线程环境中的锁定下完成,它可能会阻止其他调用。为了避免调用 clear(),我尝试了这个:
std::mutex m;
std::map<int, int> my_map; // the map which I want to clear
void func()
{
std::map<int, int> temp_map;
{
std::lock_guard<std::mutex> l(m);
temp_map = std::move(my_map);
}
}
这会将 my_map 移动到锁下的 temp_map,这将清空它。然后一旦 func 结束,temp_map 将被销毁。
这是防止长时间获取锁的更好方法吗?有任何性能影响吗?
我建议使用 swap
而不是 move
。移动的对象不能保证实际上是空的甚至可用。但是使用 swap
和一个新创建的对象,您可以确定结果:
void func()
{
std::map<int, int> temp_map;
using std::swap;
{
std::lock_guard<std::mutex> l(m);
swap(my_map, temp_map);
}
}
我正在使用 std::map 并且其中包含大量元素。如果我需要清除地图,我可以在上面调用 clear() 。清除可能需要一些时间,特别是如果在多线程环境中的锁定下完成,它可能会阻止其他调用。为了避免调用 clear(),我尝试了这个:
std::mutex m;
std::map<int, int> my_map; // the map which I want to clear
void func()
{
std::map<int, int> temp_map;
{
std::lock_guard<std::mutex> l(m);
temp_map = std::move(my_map);
}
}
这会将 my_map 移动到锁下的 temp_map,这将清空它。然后一旦 func 结束,temp_map 将被销毁。
这是防止长时间获取锁的更好方法吗?有任何性能影响吗?
我建议使用 swap
而不是 move
。移动的对象不能保证实际上是空的甚至可用。但是使用 swap
和一个新创建的对象,您可以确定结果:
void func()
{
std::map<int, int> temp_map;
using std::swap;
{
std::lock_guard<std::mutex> l(m);
swap(my_map, temp_map);
}
}