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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With