LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
per_thread_holder.h
Go to the documentation of this file.
1 #ifndef fhiclcpp_types_detail_per_thread_holder_h
2 #define fhiclcpp_types_detail_per_thread_holder_h
3 
4 #include "tbb/concurrent_hash_map.h"
5 
6 #include <thread>
7 
8 namespace fhicl::detail {
10  static size_t
11  hash(std::thread::id id)
12  {
13  static std::hash<std::thread::id> const hasher{};
14  return hasher(id);
15  }
16  static bool
17  equal(std::thread::id id1, std::thread::id id2)
18  {
19  return id1 == id2;
20  }
21  };
22  template <typename T>
24  using registry_t =
25  tbb::concurrent_hash_map<std::thread::id, T, thread_hash_compare>;
26  using accessor = typename registry_t::accessor;
27 
28  public:
29  T&
31  {
32  return slot_for(std::this_thread::get_id());
33  }
34 
35  private:
36  T&
37  slot_for(std::thread::id id)
38  {
39  // Lock held on key's map entry until the function returns.
40  accessor access_token;
41  if (not registry_.insert(access_token, id)) {
42  // Entry already exists; return cached entry.
43  return access_token->second;
44  }
45 
46  access_token->second = T{};
47  return access_token->second;
48  }
49 
51  };
52 }
53 
54 #endif /* fhiclcpp_types_detail_per_thread_holder_h */
55 
56 // Local Variables:
57 // mode: c++
58 // End:
static bool equal(std::thread::id id1, std::thread::id id2)
T & slot_for(std::thread::id id)
tbb::concurrent_hash_map< std::thread::id, T, thread_hash_compare > registry_t
typename registry_t::accessor accessor
static size_t hash(std::thread::id id)