greg7mdp / parallel-hashmap

A family of header-only, very fast and memory-friendly hashmap and btree containers.
https://greg7mdp.github.io/parallel-hashmap/
Apache License 2.0
2.53k stars 239 forks source link

`std::atomic` value type specialization #159

Closed kc9jud closed 2 years ago

kc9jud commented 2 years ago

Looking at #104, it seems to be a known issue that the value type of a *flat_hash_map cannot be a non-movable/non-copyable type for obvious reasons. However, is it worth providing either a specialization or additional parallel flat map type where the value is a std::atomic? In such a case, an operation which does not involve inserting/rehashing can be done without acquiring a mutex.

One use case I'm thinking of is where one has a large hash map with a fixed set of keys, and counts are being accumulated into the values. One could safely use the various atomic assignment/increment/decrement operations on the values.

greg7mdp commented 2 years ago

You can already do that - by default the last template parameter of parallel_flat_hash_map specifies a NullMutex which doesn't do any locking.

kc9jud commented 2 years ago

That's true, but that doesn't solve the problem of std::atomic<T> being non-movable/non-copyable. However, it looks like simply using C++20's std::atomic_ref is probably better than trying to make parallel_flat_hash_map learn how to rehash with atomics. In fact, it seems like this problem is actually what std::atomic_ref was intended to solve.

greg7mdp commented 2 years ago

Yes, I agree, std::atomic_ref seems like the best solution. Thanks for the comment @kc9jud .