I am using folly::ConccurentHashMap
and I want to have a frequency counter of std::string
Is there an API to “insert 1 if key is missing otherwise update value of 1” atomically?
I thought of
auto [it, _] = numOccurences.emplace(str, 1);
it->second = it->second + 1;
but I am not sure if it’s atomic, and it complains about const reference of the second value.
2
Because operator[]
returns a copy and iterators are not a thread-safe option, folly::ConcurrentHashMap
provides the insert_or_assign
operation as a thread-safe means by which you can perform a “insert if key isn’t present otherwise update value” operation.
/*
* The bool component will always be true if the map has been updated via
* either insertion or assignment. Note that this is different from the
* std::map::insert_or_assign interface.
*/
template <typename Key, typename Value>
std::pair<ConstIterator, bool> insert_or_assign(Key&& k, Value&& v);
In order to atomically increment a value, as correctly pointed out by @Mooning Duck in the comments, you will need to use a method like assign_if_equal
to perform an atomic CAS. There is no insert_or_assign_if_equal
, however, you can achieve this with an insert and a assign_if_equal
in a loop.
4