I have a flyweight pattern working in serial where the factory uses std::map
to store and provide access to the created objects. The factory returns an iterator
that points to the object in the map. The objects in the factory are constants, so they will not be updated once inserted, unless they are erased.
I would like to make the factory concurrent using tbb::concurrent_hash_map
, but I am unsure what the return should be. I could use an iterator
(should it be const_iterator
?), but the documentation says that all iterators are invalidated when something does a find
or insert
in the concurrent_hash_map
. So I could use a const_accessor
since only read-only access is needed, but then this is different from the serial implementation (iterator
vs accessor
).
Which one is better to use? Should consistency in types (ie. both iterators) be important? Both serial and threaded compile-time options need to be there.
If you do not erase elements simultaneously with other threads accessing the map, you may use tbb::concurrent_unordered_map
instead. This is also a hash-based associative container, but with simpler and more STL-like API. It does not invalidate iterators by insert
and find
, but as a tradeoff, it does not allow concurrent removal of elements.
If you do need to remove elements concurrently, the only choice with TBB is to use tbb::concurrent_hash_map
with accessors.
I also suggest you to discuss your use case at the TBB forum.