Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2023-03-17 11:03:50

0001 #ifndef FWCore_Utilities_CallOnceNoWait_h
0002 #define FWCore_Utilities_CallOnceNoWait_h
0003 // -*- C++ -*-
0004 //
0005 // Package:     FWCore/Utilities
0006 // Class  :     CallOnceNoWait
0007 //
0008 /**\class edm::CallOnceNoWait CallOnceNoWait.h "FWCore/Utilities/interface/CallOnceNoWait.h"
0009 
0010  Description: Thread safe way to do something 1 time
0011 
0012  Usage:
0013  This class allows one to safely do a 'non-side-effect' operation 1 time in a job.
0014  An example use would be
0015  \code
0016  void myFunc( int iValue) {
0017  static CallOnceNoWait message;
0018  message([&]() { edm::LogInfo("IWantToKnow")<<"called with "<<iValue; } );
0019  \endcode
0020  The important thing to remember, is there is no guarantee that the operation being run
0021  finishes before a thread which doesn't get to run the operation reaches the code following
0022  the call. Therefore it is useful to suppress messages but should not be used to do something
0023  like filling a container with values since the filling is not guaranteed to complete before
0024  another thread skips the call.
0025 
0026 */
0027 //
0028 // Original Author:  Chris Jones
0029 //         Created:  Fri, 15 Nov 2013 14:29:51 GMT
0030 //
0031 
0032 // system include files
0033 #include <atomic>
0034 
0035 // user include files
0036 
0037 // forward declarations
0038 
0039 namespace edm {
0040   class CallOnceNoWait {
0041   public:
0042     CallOnceNoWait() : m_called(false) {}
0043 
0044     template <typename T>
0045     void operator()(T iCall) {
0046       bool expected = false;
0047       if (m_called.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
0048         iCall();
0049       }
0050     }
0051 
0052   private:
0053     std::atomic<bool> m_called;
0054   };
0055 }  // namespace edm
0056 
0057 #endif