在锁定下清除STD ::映射,而移动到临时对象
Clearing std::map under a lock vs moving to a temp object
我使用的是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);
}
}
相关文章:
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- vector是否为std::移动的对象连续分配内存
- 临时对象上的运算符重载
- 如何在没有 std::move 的情况下移动临时对象
- 临时对象在C++中是不可避免的吗?
- 编译错误:临时对象构造函数中缺少参数
- 在锁定下清除STD ::映射,而移动到临时对象
- 临时对象的子对象是否保证在返回时移动
- 将临时对象移动到矢量中
- 移动语义以避免临时对象的创建