在锁定下清除STD ::映射,而移动到临时对象

Clearing std::map under a lock vs moving to a temp object

本文关键字:移动 临时对象 映射 清除 STD 锁定      更新时间:2023-10-16

我使用的是std ::映射,其中包含大量元素。如果需要清除地图,我可以在其上调用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,这将使它清空。然后,一旦弹性结束,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);
    }
}