Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using a std::map and have large number of elements in it. If I need to clear the map, I can just call clear() on it. It can take some time to clear and especially if done under a lock in a multi-threaded environment, it can block other calls. To avoid calling clear(), I tried this:

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);
    }
}

This will move my_map to temp_map under the lock which will empty it out. And then once the func ends, the temp_map will be destroyed.

Is this a better way to do this to prevent taking the lock for a long time? Are there any performance hits?

like image 774
kwadhwa Avatar asked Jun 22 '17 21:06

kwadhwa


1 Answers

I would recommend using swap instead of move. A moved object is not guaranteed to be actually empty or even usable. But with swap and a freshly created object you are sure of the results:

void func()
{
    std::map<int, int> temp_map;
    using std::swap;
    {
        std::lock_guard<std::mutex> l(m);
        swap(my_map, temp_map);
    }
}
like image 183
rodrigo Avatar answered Nov 15 '22 05:11

rodrigo