MapLibre Native Core
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
scheduler.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 
4 #include <mapbox/std/weak.hpp>
5 
6 #include <functional>
7 #include <memory>
8 
9 namespace mbgl {
10 
11 class Mailbox;
12 
35 class Scheduler {
36 public:
37  virtual ~Scheduler() = default;
38 
40  virtual void schedule(std::function<void()>) = 0;
42  virtual mapbox::base::WeakPtr<Scheduler> makeWeakPtr() = 0;
43 
52  std::function<void()> bindOnce(std::function<void()>);
53 
60  template <typename TaskFn, typename ReplyFn>
61  void scheduleAndReplyValue(const TaskFn& task, const ReplyFn& reply) {
62  assert(GetCurrent());
63  scheduleAndReplyValue(task, reply, GetCurrent()->makeWeakPtr());
64  }
65 
67  static Scheduler* GetCurrent();
68  static void SetCurrent(Scheduler*);
69 
76  [[nodiscard]] static std::shared_ptr<Scheduler> GetBackground();
77 
86  [[nodiscard]] static std::shared_ptr<Scheduler> GetSequenced();
87 
88 protected:
89  template <typename TaskFn, typename ReplyFn>
90  void scheduleAndReplyValue(const TaskFn& task,
91  const ReplyFn& reply,
92  mapbox::base::WeakPtr<Scheduler> replyScheduler) {
93  auto scheduled = [replyScheduler = std::move(replyScheduler), task, reply] {
94  auto lock = replyScheduler.lock();
95  if (!replyScheduler) return;
96  auto scheduledReply = [reply, result = task()] { reply(result); };
97  replyScheduler->schedule(std::move(scheduledReply));
98  };
99 
100  schedule(std::move(scheduled));
101  }
102 };
103 
104 }
virtual mapbox::base::WeakPtr< Scheduler > makeWeakPtr()=0
Makes a weak pointer to this Scheduler.
static Scheduler * GetCurrent()
Set/Get the current Scheduler for this thread.
std::function< void()> bindOnce(std::function< void()>)
virtual ~Scheduler()=default
void scheduleAndReplyValue(const TaskFn &task, const ReplyFn &reply)
Definition: scheduler.hpp:61
virtual void schedule(std::function< void()>)=0
Enqueues a function for execution.
static void SetCurrent(Scheduler *)
static std::shared_ptr< Scheduler > GetSequenced()
static std::shared_ptr< Scheduler > GetBackground()
void scheduleAndReplyValue(const TaskFn &task, const ReplyFn &reply, mapbox::base::WeakPtr< Scheduler > replyScheduler)
Definition: scheduler.hpp:90
Definition: actor.hpp:15