ATLAS Offline Software
Loading...
Searching...
No Matches
ThreadSpecificUserAction.h
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
3*/
4
5#ifndef G4ATLASTOOLS_THREADSPECIFICUSERACTION_H
6#define G4ATLASTOOLS_THREADSPECIFICUSERACTION_H
7
8// System includes
9#include <thread>
10#include <memory>
11#include <utility>
12
13// Other includes
14#include "tbb/concurrent_unordered_map.h"
15
16namespace G4UA
17{
18
29 template<class ActionType>
31 {
32
33 public:
34
35 using ThreadMapKey_t = std::thread::id;
36 using ThreadMapVal_t = ActionType*;
37 //using ThreadMapVal_t = std::unique_ptr<ActionType>; // not supported
38 using ThreadMapHash_t = std::hash<ThreadMapKey_t>;
39 using ThreadMap_t = tbb::concurrent_unordered_map
41 using const_iterator = typename ThreadMap_t::const_iterator;
42
46 for(auto& mapPair : m_threadMap){
47 delete mapPair.second;
48 }
49 m_threadMap.clear();
50 }
51
53 ActionType* get() {
54 auto mapItr = m_threadMap.find( std::this_thread::get_id() );
55 if(mapItr == m_threadMap.end()) return nullptr;
56 return mapItr->second;
57 }
58
61 void set(std::unique_ptr<ActionType> action) {
62 const auto tid = std::this_thread::get_id();
63 m_threadMap.insert( std::make_pair(tid, action.release()) );
64 }
65
68 return m_threadMap.begin();
69 }
70
73 return m_threadMap.end();
74 }
75
87 template< class ResultType, class Mapper, class Reducer >
88 void accumulate( ResultType& result, Mapper mapOp, Reducer reduceOp )
89 {
90 // Wrapping the ops in std::function allows for some constrained
91 // flexibility and avoids difficult template determination in the args.
92 std::function<const ResultType&(const ActionType&)> mapper = mapOp;
93 std::function<void(ResultType&, const ResultType&)> reducer = reduceOp;
94 // Loop over user actions and apply the functions
95 for(const auto& keyVal : m_threadMap) {
96 reducer( result, mapper(*keyVal.second) );
97 }
98 }
99
100 private:
101
104
105 }; // class ThreadSpecificUserAction
106
107} // namespace G4UA
108
109#endif // G4ATLASTOOLS_THREADSPECIFICUSERACTION_H
A thread-local storage wrapper for the user actions.
const_iterator end() const
Constant-access iteration over the action map.
typename ThreadMap_t::const_iterator const_iterator
std::hash< ThreadMapKey_t > ThreadMapHash_t
void set(std::unique_ptr< ActionType > action)
Assign the object of the current thread.
ThreadMap_t m_threadMap
The wrapped thread-local storage container.
ActionType * get()
Get the object of the current thread.
~ThreadSpecificUserAction()
Destructor will clean up the thread-local storage.
tbb::concurrent_unordered_map< ThreadMapKey_t, ThreadMapVal_t, ThreadMapHash_t > ThreadMap_t
const_iterator begin() const
Constant-access iteration over the action map.
void accumulate(ResultType &result, Mapper mapOp, Reducer reduceOp)
Accumulate results across user actions with specified operations.