distortos  v0.4.0
object-oriented C++ RTOS for microcontrollers
callOnce.hpp
Go to the documentation of this file.
1 
12 #ifndef INCLUDE_DISTORTOS_CALLONCE_HPP_
13 #define INCLUDE_DISTORTOS_CALLONCE_HPP_
14 
16 
17 #include "distortos/OnceFlag.hpp"
18 
19 #include "estd/invoke.hpp"
20 #include "estd/ScopeGuard.hpp"
21 
22 namespace distortos
23 {
24 
43 template<typename Function, typename... Args>
44 void callOnce(OnceFlag& onceFlag, Function&& function, Args&&... args)
45 {
47 
48  if (onceFlag.done_ == true)
49  return;
50 
51  onceFlag.mutex_.lock();
52  const auto mutexUnlockScopeGuard = estd::makeScopeGuard(
53  [&onceFlag]()
54  {
55  onceFlag.mutex_.unlock();
56  });
57 
58  if (onceFlag.done_ == true)
59  return;
60 
61  estd::invoke(std::forward<Function>(function), std::forward<Args>(args)...);
62  onceFlag.done_ = true;
63 }
64 
65 } // namespace distortos
66 
67 #endif // INCLUDE_DISTORTOS_CALLONCE_HPP_
int lock()
Locks the mutex.
Definition: Mutex.cpp:30
ScopeGuard< Function > makeScopeGuard(Function &&function) noexcept
Helper factory function to make ScopeGuard object with deduced template arguments.
Definition: ScopeGuard.hpp:107
ScopeGuard template class header.
CHECK_FUNCTION_CONTEXT() macro.
Mutex mutex_
internal mutex used by callOnce()
Definition: OnceFlag.hpp:50
OnceFlag class header.
void callOnce(OnceFlag &onceFlag, Function &&function, Args &&... args)
Executes the callable object exactly once, even if called from multiple threads.
Definition: callOnce.hpp:44
Top-level namespace of distortos project.
int unlock()
Unlocks the mutex.
Definition: Mutex.cpp:67
#define CHECK_FUNCTION_CONTEXT()
Macro used to check whether the function is executed from thread context.
Definition: CHECK_FUNCTION_CONTEXT.hpp:29
volatile bool done_
tells whether any function was already called for this object (true) or not (false) ...
Definition: OnceFlag.hpp:53
auto invoke(Function &&function, Args &&... args) -> decltype(internal::invoke(std::forward< Function >(function), std::forward< Args >(args)...))
Invokes callable object in an appropriate way.
Definition: invoke.hpp:139
OnceFlag is a helper class for callOnce().
Definition: OnceFlag.hpp:29
invoke() header