Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:50:14

0001 #ifndef CommonTools_Utils_ThreadSafeFunctor_H
0002 #define CommonTools_Utils_ThreadSafeFunctor_H
0003 
0004 #include "FWCore/Utilities/interface/thread_safety_macros.h"
0005 
0006 #include <mutex>
0007 #include <utility>
0008 
0009 // This class is a simple wrapper around some functor class to use its operator() in a thread-safe way.
0010 
0011 template <class Functor>
0012 class ThreadSafeFunctor {
0013 public:
0014   template <typename... Params>
0015   ThreadSafeFunctor(Params&&... params) : functor_{std::forward<Params>(params)...} {}
0016 
0017   ThreadSafeFunctor(ThreadSafeFunctor&& other) noexcept : functor_(std::move(other.functor_)) {}
0018 
0019   template <typename... Params>
0020   typename std::invoke_result_t<Functor, Params...> operator()(Params&&... params) const {
0021     std::lock_guard<std::mutex> guard(mutex_);
0022     return functor_(std::forward<Params>(params)...);
0023   }
0024 
0025 private:
0026   const Functor functor_;
0027   CMS_THREAD_SAFE mutable std::mutex mutex_;
0028 };
0029 
0030 #endif