Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2023.
[simgrid.git] / include / simgrid / kernel / Timer.hpp
1 /* Copyright (c) 2021-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SRC_KERNEL_TIMER_TIMER_HPP_
7 #define SRC_KERNEL_TIMER_TIMER_HPP_
8
9 #include <simgrid/forward.h>
10 #include <xbt/functional.hpp>
11 #include <xbt/utility.hpp>
12
13 #include <boost/heap/fibonacci_heap.hpp>
14
15 namespace simgrid {
16 namespace kernel {
17 namespace timer {
18
19 inline auto& kernel_timers() // avoid static initialization order fiasco
20 {
21   using TimerQelt = std::pair<double, Timer*>;
22   static boost::heap::fibonacci_heap<TimerQelt, boost::heap::compare<xbt::HeapComparator<TimerQelt>>> value;
23   return value;
24 }
25
26 /** @brief Timer datatype */
27 class Timer {
28   const double date_;
29   xbt::Task<void()> callback;
30   std::remove_reference_t<decltype(kernel_timers())>::handle_type handle_;
31
32 public:
33   double get_date() const { return date_; }
34
35   Timer(double date, xbt::Task<void()>&& callback) : date_(date), callback(std::move(callback)) {}
36
37   void remove();
38
39   template <class F> static inline Timer* set(double date, F callback)
40   {
41     return set(date, xbt::Task<void()>(std::move(callback)));
42   }
43
44   static Timer* set(double date, xbt::Task<void()>&& callback);
45   static double next() { return kernel_timers().empty() ? -1.0 : kernel_timers().top().first; }
46
47   /** Handle any pending timer. Returns if something was actually run. */
48   static bool execute_all();
49 };
50
51 } // namespace timer
52 } // namespace kernel
53 } // namespace simgrid
54
55 #endif /* SRC_KERNEL_TIMER_TIMER_HPP_ */