parallel_map.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2009-2021 Intel Corporation
  2. // SPDX-License-Identifier: Apache-2.0
  3. #pragma once
  4. #include "parallel_sort.h"
  5. namespace embree
  6. {
  7. /*! implementation of a key/value map with parallel construction */
  8. template<typename Key, typename Val>
  9. class parallel_map
  10. {
  11. /* key/value pair to build the map */
  12. struct KeyValue
  13. {
  14. __forceinline KeyValue () {}
  15. __forceinline KeyValue (const Key key, const Val val)
  16. : key(key), val(val) {}
  17. __forceinline operator Key() const {
  18. return key;
  19. }
  20. public:
  21. Key key;
  22. Val val;
  23. };
  24. public:
  25. /*! parallel map constructors */
  26. parallel_map () {}
  27. /*! construction from pair of vectors */
  28. template<typename KeyVector, typename ValVector>
  29. parallel_map (const KeyVector& keys, const ValVector& values) { init(keys,values); }
  30. /*! initialized the parallel map from a vector with keys and values */
  31. template<typename KeyVector, typename ValVector>
  32. void init(const KeyVector& keys, const ValVector& values)
  33. {
  34. /* reserve sufficient space for all data */
  35. assert(keys.size() == values.size());
  36. vec.resize(keys.size());
  37. /* generate key/value pairs */
  38. parallel_for( size_t(0), keys.size(), size_t(4*4096), [&](const range<size_t>& r) {
  39. for (size_t i=r.begin(); i<r.end(); i++)
  40. vec[i] = KeyValue((Key)keys[i],values[i]);
  41. });
  42. /* perform parallel radix sort of the key/value pairs */
  43. std::vector<KeyValue> temp(keys.size());
  44. radix_sort<KeyValue,Key>(vec.data(),temp.data(),keys.size());
  45. }
  46. /*! Returns a pointer to the value associated with the specified key. The pointer will be nullptr of the key is not contained in the map. */
  47. __forceinline const Val* lookup(const Key& key) const
  48. {
  49. typename std::vector<KeyValue>::const_iterator i = std::lower_bound(vec.begin(), vec.end(), key);
  50. if (i == vec.end()) return nullptr;
  51. if (i->key != key) return nullptr;
  52. return &i->val;
  53. }
  54. /*! If the key is in the map, the function returns the value associated with the key, otherwise it returns the default value. */
  55. __forceinline Val lookup(const Key& key, const Val& def) const
  56. {
  57. typename std::vector<KeyValue>::const_iterator i = std::lower_bound(vec.begin(), vec.end(), key);
  58. if (i == vec.end()) return def;
  59. if (i->key != key) return def;
  60. return i->val;
  61. }
  62. /*! clears all state */
  63. void clear() {
  64. vec.clear();
  65. }
  66. private:
  67. std::vector<KeyValue> vec; //!< vector containing sorted elements
  68. };
  69. }